﻿using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Net;
using System.Reflection;
using System.Windows.Forms;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;

using Srvtools;
using FLTools;
using System.IO.Compression;

namespace EEPNetFLClient
{
    public partial class frmClientFL : InfoForm ,IShowForm 
    {
        private frmLogin fFrmLogin = null;
        string[] lstStatus = null;
        public bool IgnoreWeekends = true;
        private DataSet menuFavorDataSet;
        private DataSet groupFavorDataSet;
        private DataSet menuDataSet;
        public const int TreeViewLevel = 2;
        private FormCollection fFormCollection;

        public frmClientFL()
        {            
            InitializeComponent();
            frmClientFL.CheckForIllegalCrossThreadCalls = false; 
            fFormCollection=new FormCollection(this,typeof(FormItem));
            this.Activated += new EventHandler(frmClientFL_Activated);
            this.HelpRequested += new HelpEventHandler(frmClientFL_HelpRequested);
            InitializeForm();
            CliUtils.fCliMainHandle = this.Handle;            
        }
               
        private void InitializeForm()
        {
            string picPath="";           
            picPath = Application.StartupPath + "\\Config\\default.PNG";
            if (File.Exists(picPath))
            {
                this.panel7.BackgroundImage  = Image.FromFile(picPath);
            }                                           
            this.miVwTreeMenu.Checked = EEPNetFLClient.Properties.Settings.Default.ShowTree == "1"?true:false;
            this.scMaster.Panel1Collapsed  = !this.miVwTreeMenu.Checked;
            this.scMaster.SplitterDistance = EEPNetFLClient.Properties.Settings.Default.TreeWidth;
            if (this.scMaster.SplitterDistance<= 30)
            {
                this.pictureBox1.Image = global::EEPNetFLClient.Properties.Resources.d1;
                flag = true;
                sx = 200;
            }

            this.miVwWFManage.Checked = EEPNetFLClient.Properties.Settings.Default.ShowFL == "1" ? true : false;
            this.tmFlow.Enabled = this.miVwWFManage.Checked;
            this.panFLContainer.Visible = this.miVwWFManage.Checked;
            this.panFLContainer.Height = EEPNetFLClient.Properties.Settings.Default.FLHeight;
            if (this.panFLContainer.Height <= 20)
            {
                this.pictureBox2.Image = global::EEPNetFLClient.Properties.Resources.d3;
                flag1 = true;
                sizY = 200;
            }
            this.miVwSatatusBar.Checked = EEPNetFLClient.Properties.Settings.Default.ShowStaBar == "1" ? true : false;
            this.staMain.Visible = this.miVwSatatusBar.Checked;
            this.miUpdateCache.Checked = EEPNetFLClient.Properties.Settings.Default.AlwaysUpdateCache;
            AssemblyDescriptionAttribute
                description = (AssemblyDescriptionAttribute)AssemblyDescriptionAttribute.GetCustomAttribute(
                System.Reflection.Assembly.GetExecutingAssembly(), typeof(AssemblyDescriptionAttribute));
            this.Text += " " + description.Description;
        }

        private void frmClientFL_Load(object sender, EventArgs e)
        {            
            try
            {
                bool freg = false;
                try
                {
                    freg = Register(false);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }                                
                fFrmLogin = new frmLogin(freg);
                if (fFrmLogin.ShowDialog() == DialogResult.OK)
                {                    
                    if (freg == false)
                    {
                        if (!Register(true))
                        {
                            this.Close();
                        }
                    }
                    CheckUser();
                    LoadCachDataSet(null,null);
                    SetMenuText();
                    SetStatusText();                    
                    this.WindowState = FormWindowState.Maximized;                    
                }
                else
                {
                    CliUtils.fLoginUser = string.Empty;
                    Close();
                }
            }
            catch(Exception ex)
            {
                frmWaiting.CloseWaiting();
                MessageBox.Show(ex.Message, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.Exit();
            }
        }
               
        private bool Register(bool isShowMessage)
        {
            string message = "";
            bool rtn = CliUtils.Register(ref message);
            if (rtn)
            {
                CliUtils.GetSysXml(Application.StartupPath + @"\sysmsg.xml");
            }
            else
            {
                if (isShowMessage)
                {
                    MessageBox.Show(message);
                }
            }
            return rtn;
        }

        private void CheckUser()
        {
            CheckUser(false);
        }

        private void CheckUser(bool relogin)
        {
            CliUtils.fLoginUser = fFrmLogin.GetUserId();
            CliUtils.fLoginPassword = fFrmLogin.GetPwd();
            CliUtils.fLoginDB = fFrmLogin.GetDB();
            CliUtils.fCurrentProject = fFrmLogin.GetCurProject();
            LoginResult result = LoginResult.Success;
            if (CliUtils.fLoginUser.Contains("'"))
            {
                result = LoginResult.UserNotFound;
            }
            else
            {
                string sParam = CliUtils.fLoginUser + ':' + CliUtils.fLoginPassword + ':' + CliUtils.fLoginDB;
                if (relogin)
                {
                    sParam += ":1";
                }
                else
                {
                    sParam += ":0";
                }
                object[] myRet = CliUtils.CallMethod("GLModule", "CheckUser", new object[] { (object)sParam });
                if (myRet!=null && (int)myRet[0] == 0)
                {
                    result = (LoginResult)myRet[1];
                    switch (result)
                    {
                        case LoginResult.UserNotFound:
                            {
                                string message = SysMsg.GetSystemMessage(CliUtils.fClientLang, "EEPWebNetClient", "WinSysMsg", "msg_UserNotFound");
                                MessageBox.Show(this, message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                break;
                            }
                        case LoginResult.PasswordError:
                            {
                                string message = SysMsg.GetSystemMessage(CliUtils.fClientLang, "EEPWebNetClient", "WinSysMsg", "msg_UserOrPasswordError");
                                MessageBox.Show(this, message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                break;
                            }
                        case LoginResult.UserLogined:
                            {
                                string message = SysMsg.GetSystemMessage(CliUtils.fClientLang, "EEPWebNetClient", "WinSysMsg", "msg_UserIsLogined");
                                MessageBox.Show(this, string.Format(message, CliUtils.fLoginUser), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                break;
                            }
                        case LoginResult.RequestReLogin:
                            {
                                string message = SysMsg.GetSystemMessage(CliUtils.fClientLang, "EEPWebNetClient", "WinSysMsg", "msg_UserReLogined");
                                if (MessageBox.Show(string.Format(message, CliUtils.fLoginUser)
                                    , "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                                {
                                    CheckUser(true);
                                }
                                else
                                {
                                    CliUtils.fLoginUser = string.Empty;
                                    this.Close();
                                }
                                return;
                            }
                        default:
                            {
                                if (CliUtils.fPassWordNotify != 0)
                                    CheckPassword(CliUtils.fLoginUser);

                                object[] isTableExist = CliUtils.CallMethod("GLModule", "isTableExist", new object[] { "MENUFAVOR" });
                                if (isTableExist != null && Convert.ToInt16(isTableExist[0]) == 0 && Convert.ToInt16(isTableExist[1]) == 1)
                                    panel10.Visible = false;

                                CliUtils.fUserName = myRet[2].ToString();
                                CliUtils.fLoginUser = myRet[3].ToString();
                                CliUtils.GetPasswordPolicy();
                                myRet = CliUtils.CallMethod("GLModule", "GetUserGroup", new object[] { CliUtils.fLoginUser });
                                if (myRet != null && (int)myRet[0] == 0)
                                {
                                    CliUtils.fGroupID = myRet[1].ToString();
                                }
                                myRet = CliUtils.CallMethod("GLModule", "GetUserRole", new object[] { });
                                if (myRet != null && (int)myRet[0] == 0)
                                {
                                    CliUtils.Roles = myRet[1].ToString();
                                    CliUtils.OrgRoles = myRet[2].ToString();
                                    CliUtils.OrgShares = myRet[3].ToString();
                                }
                                DoLoad();
                                Startup.SaveToClientXML(CliUtils.fLoginUser, CliUtils.fLoginDB, CliUtils.fCurrentProject);
                                LoadWF();
                                break;
                            }
                    }
                }
            }
            if (result != LoginResult.Success)
            {
                if (fFrmLogin.ShowDialog(this) == DialogResult.OK)
                {
                    CheckUser();
                }
                else
                {
                    CliUtils.fLoginUser = string.Empty;
                    this.Close();
                }
            }
        }

        private void SetMenuText()
        {
            string menutext = SysMsg.GetSystemMessage(CliUtils.fClientLang, "EEPNetClient", "FrmClientMain", "Menu");
            if (menutext.Length > 0)
            {
                string[] list = menutext.Split(';');
                systemToolStripMenuItem.Text = list[0].Replace("_", "&");
                solutionToolStripMenuItem.Text = list[1].Replace("_", "&");
                dataBaseToolStripMenuItem.Text = list[2].Replace("_", "&");
                changePasswordToolStripMenuItem.Text = list[3].Replace("_", "&");
                exitToolStripMenuItem.Text = list[4].Replace("_", "&");
                windowsToolStripMenuItem.Text = list[5].Replace("_", "&");
                helpToolStripMenuItem.Text = list[9].Replace("_", "&");
                aboutEEPNetClientToolStripMenuItem.Text = list[10].Replace("_", "&");
                this.miVw.Text = list[11].Replace("_","&");
                this.miVwTreeMenu.Text = list[12].Replace("_", "&");
                this.miVwWFManage.Text = list[13].Replace("_", "&");
                this.miVwSatatusBar.Text = list[14].Replace("_", "&");
                this.wmiCloseAll.Text = list[15].Replace("_", "&");
                this.miUpdateCache.Text = list[16].Replace("_", "&");
                this.miHelpDir.Text = list[17].Replace("_", "&");
                this.miHelpIndex.Text = list[18].Replace("_", "&");
            }
        }

        private void SetStatusText()
        {
            this.staMain.Items[0].Text = String.Format("工程名称:[{0}]", Srvtools.CliUtils.fCurrentProject);
            this.staMain.Items[1].Text = String.Format("数据库:[{0}]", Srvtools.CliUtils.fLoginDB);
            this.staMain.Items[2].Text = String.Format("当前用户:[{0}]", Srvtools.CliUtils.fLoginUser);
            this.staMain.Items[3].Text = String.Format("用户名称:[{0}]", Srvtools.CliUtils.fUserName);
            object[] myRet = CliUtils.CallMethod("GLModule", "GetServerTime", new object[] { });
            if (myRet != null && (int)myRet[0] == 0)
            {
                this.staMain.Items[4].Text = String.Format("登录时间:[{0}]", myRet[1].ToString() + " " + myRet[2].ToString());
            }
        }

        private void LoadWF()
        {
            string selOption = SysMsg.GetSystemMessage(CliUtils.fClientLang, "EEPNetClient", "FrmClientMain", "SelectOption");

            DataTable list = null;
            object[] ret1 = CliUtils.CallMethod("GLModule", "ExcuteWorkFlow", new object[] { "SELECT DISTINCT SYS_TODOLIST.FLOW_DESC FROM SYS_TODOLIST" });
            if (ret1 != null && (int)ret1[0] == 0)
            {
                list = ((DataSet)ret1[1]).Tables[0];
            }

            this.fillCombo(this.cmbToDoListFilter, list, "FLOW_DESC", selOption);
            this.cmbToDoListFilter.SelectedIndexChanged += new EventHandler(cmbToDoListFilter_SelectedIndexChanged);

            this.fillCombo(this.cmbNotifyFilter, list, "FLOW_DESC", selOption);
            this.cmbNotifyFilter.SelectedIndexChanged += new EventHandler(cmbNotifyFilter_SelectedIndexChanged);

            this.fillCombo(this.cmbToDoHisFilter, list, "FLOW_DESC", selOption);
            this.cmbToDoHisFilter.SelectedIndexChanged += new EventHandler(cmbToDoHisFilter_SelectedIndexChanged);

            this.fillCombo(this.cmbLstFlow, list, "FLOW_DESC", selOption);

            this.fillCombo(this.cmbHisFlow, list, "FLOW_DESC", selOption);

            this.fillCombo(this.cmbHis2Flow, list, "FLOW_DESC", selOption);

            DataTable users = null;
            object[] ret2 = CliUtils.CallMethod("GLModule", "ExcuteWorkFlow", new object[] { "SELECT USERS.USERID, USERS.USERNAME FROM USERS WHERE USERS.USERID IN (SELECT USERGROUPS.USERID FROM USERGROUPS WHERE USERGROUPS.GROUPID IN(SELECT GROUPS.GROUPID FROM GROUPS WHERE GROUPS.ISROLE='Y'))" });
            if (ret2 != null && (int)ret2[0] == 0)
            {
                users = ((DataSet)ret2[1]).Tables[0];
            }
            this.fillCombo(this.cmbLstUser, users, "USERNAME", selOption);

            DataTable roles = null;
            object[] ret3 = CliUtils.CallMethod("GLModule", "ExcuteWorkFlow", new object[] { "SELECT GROUPID, GROUPNAME FROM GROUPS WHERE ISROLE='Y'" });
            if (ret3 != null && (int)ret3[0] == 0)
            {
                roles = ((DataSet)ret3[1]).Tables[0];
            }
            this.fillCombo(this.cmbHisSendTo, roles, "GROUPNAME", selOption);


            this.dgvToDoList.AutoGenerateColumns = false;
            this.dgvToDoHis.AutoGenerateColumns = false;
            this.dgvNotify.AutoGenerateColumns = false;
            this.dgvOvertime.AutoGenerateColumns = false;

            this.wizToDoList.Refresh();
            this.wizToDoHis.Refresh();
            this.wizNotify.Refresh();

            setToDoListColumns();
            setToDoHistColumns();
            setNotifyColumns();
            setOvertimeColumns();

            this.cmbLevel.SelectedIndex = 2;

            setToDoListOvertimeWarning();
            setToDoHisOvertimeWarning();
            setNotifyOvertimeWarning();

            string[] overtimeCols = SysMsg.GetSystemMessage(CliUtils.fClientLang, "EEPNetClient", "FrmClientMain", "OvertimeColumns").Split(',');
            this.lblLevel.Text = overtimeCols[7];
            this.chkActive.Text = overtimeCols[8];

            string[] uiTexts = SysMsg.GetSystemMessage(CliUtils.fClientLang, "Web", "webClientMainFlow", "UIText").Split(';');
            this.lnkToDoListRefresh.Text = uiTexts[1];
            this.lnkToDoHisRefresh.Text = uiTexts[1];
            this.lnkNotifyRefresh.Text = uiTexts[1];
            this.lnkOvertimeRefresh.Text = uiTexts[1];
            this.lnkToDoListQuery.Text = uiTexts[17];
            this.lnkToDoHisQuery.Text = uiTexts[17];
            this.tabPage1.Text = uiTexts[2];
            this.tabPage2.Text = uiTexts[3];
            this.tabPage3.Text = uiTexts[4];
            this.tabPage4.Text = uiTexts[16];
            //cmsToDoList
            this.approveToolStripMenuItem.Text = uiTexts[6];
            this.rejectToolStripMenuItem.Text = uiTexts[7];
            this.returnToolStripMenuItem.Text = uiTexts[8];
            this.openToolStripMenuItem.Text = uiTexts[9];
            this.refreshToolStripMenuItem.Text = uiTexts[10];
            //cmsToDoHis
            this.returnToolStripMenuItem1.Text = uiTexts[14];
            this.openToolStripMenuItem1.Text = uiTexts[9];
            this.refreshToolStripMenuItem1.Text = uiTexts[10];
            //cmsNotify
            this.openToolStripMenuItem2.Text = uiTexts[9];
            this.deleteToolStripMenuItem.Text = uiTexts[15];
            this.refreshToolStripMenuItem2.Text = uiTexts[10];

            string[] queryCaptions = SysMsg.GetSystemMessage(CliUtils.fClientLang, "Web", "webClientMainFlow", "QueryCaption").Split(';');
            this.lblLstFlow.Text = queryCaptions[0];
            this.lblLstDstep.Text = queryCaptions[1];
            this.lblLstUser.Text = queryCaptions[2];
            this.lblLstFormPresent.Text = queryCaptions[3];
            this.lblLstRemark.Text = queryCaptions[4];
            this.lblLstDateFrom.Text = queryCaptions[5];
            this.lblLstDateTo.Text = queryCaptions[6];
            this.btnLstQueryOK.Text = queryCaptions[9];
            this.btnLstQueryCancel.Text = queryCaptions[10];

            this.lblHisFlow.Text = queryCaptions[0];
            this.lblHisDstep.Text = queryCaptions[1];
            this.lblHisSendTo.Text = queryCaptions[7];
            this.lblHisFormPresent.Text = queryCaptions[3];
            this.lblHisDateFrom.Text = queryCaptions[5];
            this.lblHisDateTo.Text = queryCaptions[6];
            this.lblHisRemark.Text = queryCaptions[4];
            this.btnHisQueryOK.Text = queryCaptions[9];
            this.btnHisQueryCancel.Text = queryCaptions[10];

            this.lblHis2Flow.Text = queryCaptions[0];
            this.lblHis2Dstep.Text = queryCaptions[1];
            this.lblHis2FormPresent.Text = queryCaptions[3];
            this.lblHis2DateFrom.Text = queryCaptions[5];
            this.lblHis2DateTo.Text = queryCaptions[6];
            this.lblHis2Remark.Text = queryCaptions[4];
            this.btnHis2QueryOK.Text = queryCaptions[9];
            this.btnHis2QueryCancel.Text = queryCaptions[10];

            this.chkActive.Checked = true;

            lstStatus = SysMsg.GetSystemMessage(CliUtils.fClientLang, "FLDesigner", "FLDesigner", "Item3").Split(',');
        }

        private void fillCombo(ComboBox combo, DataTable src, string field, string prompt)
        {
            combo.Items.Add("<--" + prompt + "-->");
            foreach (DataRow row in src.Rows)
            {
                combo.Items.Add(row[field].ToString());
            }
            combo.SelectedIndex = 0;
        }

        private bool IsOverTime(DataRowView row)
        {
            string TIME_UNIT = row["TIME_UNIT"].ToString();
            string FLOWURGENT = row["FLOWURGENT"].ToString();
            string UPDATE_WHOLE_TIME = row["UPDATE_WHOLE_TIME"].ToString();
            string UPDATE_DATE = UPDATE_WHOLE_TIME.Substring(0, UPDATE_WHOLE_TIME.IndexOf(' '));
            string UPDATE_TIME = UPDATE_WHOLE_TIME.Substring(UPDATE_WHOLE_TIME.IndexOf(' ') + 1);
            string URGENT_TIME = row["URGENT_TIME"].ToString();
            string EXP_TIME = row["EXP_TIME"].ToString();

            if (TIME_UNIT == "Day" && FLOWURGENT == "1")
            {
                if (Convert.ToDecimal(URGENT_TIME) == Decimal.Zero) return false;
                TimeSpan span = WorkTimeSpan(DateTime.Now.Date, Convert.ToDateTime(UPDATE_DATE), this.IgnoreWeekends, null);
                int overtimes = span.Days - Convert.ToInt32(Convert.ToDecimal(URGENT_TIME));
                if (overtimes >= 0)
                {
                    return true;
                }
            }
            else if (TIME_UNIT == "Day" && FLOWURGENT == "0")
            {
                if (Convert.ToDecimal(EXP_TIME) == Decimal.Zero) return false;
                TimeSpan span = WorkTimeSpan(DateTime.Now.Date, Convert.ToDateTime(UPDATE_DATE), this.IgnoreWeekends, null);
                int overtimes = span.Days - Convert.ToInt32(Convert.ToDecimal(EXP_TIME));
                if (overtimes >= 0)
                {
                    return true;
                }
            }
            else if (TIME_UNIT == "Hour" && FLOWURGENT == "1")
            {
                if (Convert.ToDecimal(URGENT_TIME) == Decimal.Zero) return false;
                TimeSpan spanDay = WorkTimeSpan(DateTime.Now.Date, Convert.ToDateTime(UPDATE_DATE), this.IgnoreWeekends, null);
                int spanHour = DateTime.Now.Hour - Convert.ToDateTime(UPDATE_TIME).Hour;
                int overtimes = spanDay.Days * 8 + spanHour - Convert.ToInt32(Convert.ToDecimal(URGENT_TIME));
                if (overtimes >= 0)
                {
                    return true;
                }
            }
            else if (TIME_UNIT == "Hour" && FLOWURGENT == "0")
            {
                if (Convert.ToDecimal(EXP_TIME) == Decimal.Zero) return false;
                TimeSpan spanDay = WorkTimeSpan(DateTime.Now.Date, Convert.ToDateTime(UPDATE_DATE), this.IgnoreWeekends, null);
                int spanHour = DateTime.Now.Hour - Convert.ToDateTime(UPDATE_TIME).Hour;
                int overtimes = spanDay.Days * 8 + spanHour - Convert.ToInt32(Convert.ToDecimal(EXP_TIME));
                if (overtimes >= 0)
                {
                    return true;
                }
            }
            return false;
        }

        private void cmbToDoListFilter_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbToDoListFilter.SelectedIndex > 0)
            {
                this.wizToDoList.Filter = "SYS_TODOLIST.FLOW_DESC='" + cmbToDoListFilter.Text + "'";
                this.wizToDoList.Refresh();
                this.setToDoListOvertimeWarning();
            }
        }

        private void cmbNotifyFilter_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbNotifyFilter.SelectedIndex > 0)
            {
                this.wizNotify.Filter = "SYS_TODOLIST.FLOW_DESC='" + cmbNotifyFilter.Text + "'";
                this.wizNotify.Refresh();
                this.setNotifyOvertimeWarning();
            }
        }

        private void cmbToDoHisFilter_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbToDoHisFilter.SelectedIndex > 0)
            {
                //this.wizToDoHis.Filter = "SYS_TODOLIST.FLOW_DESC='" + cmbToDoHisFilter.Text + "'";
                if (wizToDoHis.SqlMode == FLTools.ESqlMode.ToDoHis)
                    this.wizToDoHis.Filter = "SYS_TODOLIST.FLOW_DESC='" + cmbToDoHisFilter.Text + "'";
                else if (wizToDoHis.SqlMode == FLTools.ESqlMode.FlowRunOver)
                    this.wizToDoHis.Filter = "SYS_TODOHIS.FLOW_DESC='" + cmbToDoHisFilter.Text + "'";
            }
            else
                this.wizToDoHis.Filter = "";
            this.wizToDoHis.Refresh();
            if (this.wizToDoHis.SqlMode == ESqlMode.ToDoHis)
            {
                this.setToDoHisOvertimeWarning();
            }
        }

        private void setToDoListColumns()
        {
            DataGridViewImageColumn urgentColumn = new DataGridViewImageColumn(false);
            urgentColumn.Name = "colUrgent";
            urgentColumn.HeaderText = "";
            urgentColumn.Image = global::EEPNetFLClient.Properties.Resources._064160;
            urgentColumn.Width = 20;
            urgentColumn.Frozen = true;
            this.dgvToDoList.Columns.Insert(0, urgentColumn);

            DataGridViewImageColumn importantColumn = new DataGridViewImageColumn(false);
            importantColumn.Name = "colImportant";
            importantColumn.HeaderText = "";
            importantColumn.Image = global::EEPNetFLClient.Properties.Resources._064080;
            importantColumn.Width = 20;
            importantColumn.Frozen = true;
            this.dgvToDoList.Columns.Insert(0, importantColumn);

            string[] toDoListCols = SysMsg.GetSystemMessage(CliUtils.fClientLang, "EEPNetClient", "FrmClientMain", "ToDoListColumns").Split(',');
            //FLOW_DESC
            DataGridViewTextBoxColumn flDescColumn = new DataGridViewTextBoxColumn();
            flDescColumn.Name = "colFlDesc";
            flDescColumn.HeaderText = toDoListCols[0];
            flDescColumn.Width = 130;
            flDescColumn.DataPropertyName = "FLOW_DESC";
            this.dgvToDoList.Columns.Add(flDescColumn);
            //D_STEP_ID
            DataGridViewTextBoxColumn dStepIdColumn = new DataGridViewTextBoxColumn();
            dStepIdColumn.Name = "colDStepId";
            dStepIdColumn.HeaderText = toDoListCols[1];
            dStepIdColumn.Width = 80;
            dStepIdColumn.DataPropertyName = "D_STEP_ID";
            this.dgvToDoList.Columns.Add(dStepIdColumn);
            //FORM_PRESENTATION_CT
            DataGridViewTextBoxColumn formPresentationCtColumn = new DataGridViewTextBoxColumn();
            formPresentationCtColumn.Name = "colFormPresentationCT";
            formPresentationCtColumn.HeaderText = toDoListCols[2];
            formPresentationCtColumn.Width = 150;
            formPresentationCtColumn.DataPropertyName = "FORM_PRESENT_CT";
            this.dgvToDoList.Columns.Add(formPresentationCtColumn);
            //USERNAME
            DataGridViewTextBoxColumn userNameColumn = new DataGridViewTextBoxColumn();
            userNameColumn.Name = "colUserName";
            userNameColumn.HeaderText = toDoListCols[3];
            userNameColumn.Width = 80;
            userNameColumn.DataPropertyName = "USERNAME";
            this.dgvToDoList.Columns.Add(userNameColumn);
            //REMARK
            DataGridViewTextBoxColumn remarkColumn = new DataGridViewTextBoxColumn();
            remarkColumn.Name = "colRemark";
            remarkColumn.HeaderText = toDoListCols[4];
            remarkColumn.Width = 120;
            remarkColumn.DataPropertyName = "REMARK";
            this.dgvToDoList.Columns.Add(remarkColumn);
            //UPDATE_WHOLE_TIME
            DataGridViewTextBoxColumn updateWholeTimeColumn = new DataGridViewTextBoxColumn();
            updateWholeTimeColumn.Name = "colUpdateWholeTime";
            updateWholeTimeColumn.HeaderText = toDoListCols[5];
            updateWholeTimeColumn.Width = 120;
            updateWholeTimeColumn.DataPropertyName = "UPDATE_WHOLE_TIME";
            this.dgvToDoList.Columns.Add(updateWholeTimeColumn);
            //STATUS
            DataGridViewTextBoxColumn statusColumn = new DataGridViewTextBoxColumn();
            statusColumn.Name = "colStatus";
            statusColumn.HeaderText = toDoListCols[6];
            statusColumn.Width = 80;
            statusColumn.DataPropertyName = "STATUS";
            this.dgvToDoList.Columns.Add(statusColumn);
        }

        private void setToDoHistColumns()
        {
            this.dgvToDoHis.Columns.Clear();
            if (this.wizToDoHis.SqlMode == ESqlMode.ToDoHis)
            {
                #region ToDoHis
                DataGridViewImageColumn urgentColumn = new DataGridViewImageColumn(false);
                urgentColumn.Name = "colUrgent";
                urgentColumn.HeaderText = "";
                urgentColumn.Image = global::EEPNetFLClient.Properties.Resources._064160;
                urgentColumn.Width = 20;
                urgentColumn.Frozen = true;
                this.dgvToDoHis.Columns.Insert(0, urgentColumn);

                DataGridViewImageColumn importantColumn = new DataGridViewImageColumn(false);
                importantColumn.Name = "colImportant";
                importantColumn.HeaderText = "";
                importantColumn.Image = global::EEPNetFLClient.Properties.Resources._064080;
                importantColumn.Width = 20;
                importantColumn.Frozen = true;
                this.dgvToDoHis.Columns.Insert(0, importantColumn);

                string[] toDoListCols = SysMsg.GetSystemMessage(CliUtils.fClientLang, "EEPNetClient", "FrmClientMain", "ToDoListColumns").Split(',');
                this.chkSubmitted.Text = toDoListCols[10];
                //FLOW_DESC
                DataGridViewTextBoxColumn flDescColumn = new DataGridViewTextBoxColumn();
                flDescColumn.Name = "colFlDesc";
                flDescColumn.HeaderText = toDoListCols[0];
                flDescColumn.Width = 100;
                flDescColumn.DataPropertyName = "FLOW_DESC";
                this.dgvToDoHis.Columns.Add(flDescColumn);
                //D_STEP_ID
                DataGridViewTextBoxColumn dStepIdColumn = new DataGridViewTextBoxColumn();
                dStepIdColumn.Name = "colDStepId";
                dStepIdColumn.HeaderText = toDoListCols[1];
                dStepIdColumn.Width = 80;
                dStepIdColumn.DataPropertyName = "D_STEP_ID";
                this.dgvToDoHis.Columns.Add(dStepIdColumn);
                //FORM_PRESENTATION_CT
                DataGridViewTextBoxColumn formPresentationCtColumn = new DataGridViewTextBoxColumn();
                formPresentationCtColumn.Name = "colFormPresentationCT";
                formPresentationCtColumn.HeaderText = toDoListCols[2];
                formPresentationCtColumn.Width = 100;
                formPresentationCtColumn.DataPropertyName = "FORM_PRESENT_CT";
                this.dgvToDoHis.Columns.Add(formPresentationCtColumn);
                //SENDTO_NAME
                DataGridViewTextBoxColumn sendToNameColumn = new DataGridViewTextBoxColumn();
                sendToNameColumn.Name = "colSendToName";
                sendToNameColumn.HeaderText = toDoListCols[7];
                sendToNameColumn.Width = 80;
                sendToNameColumn.DataPropertyName = "SENDTO_NAME";
                this.dgvToDoHis.Columns.Add(sendToNameColumn);
                //REMARK
                DataGridViewTextBoxColumn remarkColumn = new DataGridViewTextBoxColumn();
                remarkColumn.Name = "colRemark";
                remarkColumn.HeaderText = toDoListCols[4];
                remarkColumn.Width = 120;
                remarkColumn.DataPropertyName = "REMARK";
                this.dgvToDoHis.Columns.Add(remarkColumn);
                //UPDATE_WHOLE_TIME
                DataGridViewTextBoxColumn updateWholeTimeColumn = new DataGridViewTextBoxColumn();
                updateWholeTimeColumn.Name = "colUpdateWholeTime";
                updateWholeTimeColumn.HeaderText = toDoListCols[5];
                updateWholeTimeColumn.Width = 120;
                updateWholeTimeColumn.DataPropertyName = "UPDATE_WHOLE_TIME";
                this.dgvToDoHis.Columns.Add(updateWholeTimeColumn);
                //STATUS
                DataGridViewTextBoxColumn statusColumn = new DataGridViewTextBoxColumn();
                statusColumn.Name = "colStatus";
                statusColumn.HeaderText = toDoListCols[6];
                statusColumn.Width = 80;
                statusColumn.DataPropertyName = "STATUS";
                this.dgvToDoHis.Columns.Add(statusColumn);
                #endregion
            }
            else if (this.wizToDoHis.SqlMode == ESqlMode.FlowRunOver)
            {
                #region FlowRunOver
                string[] toDoListCols = SysMsg.GetSystemMessage(CliUtils.fClientLang, "EEPNetClient", "FrmClientMain", "ToDoListColumns").Split(',');
                this.chkSubmitted.Text = toDoListCols[10];
                //FLOW_DESC
                DataGridViewTextBoxColumn flDescColumn = new DataGridViewTextBoxColumn();
                flDescColumn.Name = "colFlDesc";
                flDescColumn.HeaderText = toDoListCols[0];
                flDescColumn.Width = 100;
                flDescColumn.DataPropertyName = "FLOW_DESC";
                this.dgvToDoHis.Columns.Add(flDescColumn);
                //D_STEP_ID
                DataGridViewTextBoxColumn stepIdColumn = new DataGridViewTextBoxColumn();
                stepIdColumn.Name = "colStepId";
                stepIdColumn.HeaderText = toDoListCols[1];
                stepIdColumn.Width = 100;
                stepIdColumn.DataPropertyName = "D_STEP_ID";
                this.dgvToDoHis.Columns.Add(stepIdColumn);
                //FORM_PRESENT_CT
                DataGridViewTextBoxColumn formPresentationCtColumn = new DataGridViewTextBoxColumn();
                formPresentationCtColumn.Name = "colFormPresentationCT";
                formPresentationCtColumn.HeaderText = toDoListCols[2];
                formPresentationCtColumn.Width = 100;
                formPresentationCtColumn.DataPropertyName = "FORM_PRESENT_CT";
                this.dgvToDoHis.Columns.Add(formPresentationCtColumn);
                //REMARK
                DataGridViewTextBoxColumn remarkColumn = new DataGridViewTextBoxColumn();
                remarkColumn.Name = "colRemark";
                remarkColumn.HeaderText = toDoListCols[4];
                remarkColumn.Width = 120;
                remarkColumn.DataPropertyName = "REMARK";
                this.dgvToDoHis.Columns.Add(remarkColumn);
                //UPDATE_WHOLE_TIME
                DataGridViewTextBoxColumn updateWholeTimeColumn = new DataGridViewTextBoxColumn();
                updateWholeTimeColumn.Name = "colUpdateWholeTime";
                updateWholeTimeColumn.HeaderText = toDoListCols[5];
                updateWholeTimeColumn.Width = 120;
                updateWholeTimeColumn.DataPropertyName = "UPDATE_WHOLE_TIME";
                this.dgvToDoHis.Columns.Add(updateWholeTimeColumn);
                #endregion
            }
        }

        private void setNotifyColumns()
        {
            DataGridViewImageColumn urgentColumn = new DataGridViewImageColumn(false);
            urgentColumn.Name = "colUrgent";
            urgentColumn.HeaderText = "";
            urgentColumn.Image = global::EEPNetFLClient.Properties.Resources._064160;
            urgentColumn.Width = 20;
            urgentColumn.Frozen = true;
            this.dgvNotify.Columns.Insert(0, urgentColumn);

            DataGridViewImageColumn importantColumn = new DataGridViewImageColumn(false);
            importantColumn.Name = "colImportant";
            importantColumn.HeaderText = "";
            importantColumn.Image = global::EEPNetFLClient.Properties.Resources._064080;
            importantColumn.Width = 20;
            importantColumn.Frozen = true;
            this.dgvNotify.Columns.Insert(0, importantColumn);

            string[] toDoListCols = SysMsg.GetSystemMessage(CliUtils.fClientLang, "EEPNetClient", "FrmClientMain", "ToDoListColumns").Split(',');
            //FLOW_DESC
            DataGridViewTextBoxColumn flDescColumn = new DataGridViewTextBoxColumn();
            flDescColumn.Name = "colFlDesc";
            flDescColumn.HeaderText = toDoListCols[0];
            flDescColumn.Width = 100;
            flDescColumn.DataPropertyName = "FLOW_DESC";
            this.dgvNotify.Columns.Add(flDescColumn);
            //D_STEP_ID
            DataGridViewTextBoxColumn dStepIdColumn = new DataGridViewTextBoxColumn();
            dStepIdColumn.Name = "colDStepId";
            dStepIdColumn.HeaderText = toDoListCols[1];
            dStepIdColumn.Width = 80;
            dStepIdColumn.DataPropertyName = "D_STEP_ID";
            this.dgvNotify.Columns.Add(dStepIdColumn);
            //FORM_PRESENTATION_CT
            DataGridViewTextBoxColumn formPresentationCtColumn = new DataGridViewTextBoxColumn();
            formPresentationCtColumn.Name = "colFormPresentationCT";
            formPresentationCtColumn.HeaderText = toDoListCols[2];
            formPresentationCtColumn.Width = 100;
            formPresentationCtColumn.DataPropertyName = "FORM_PRESENT_CT";
            this.dgvNotify.Columns.Add(formPresentationCtColumn);
            //USERNAME
            DataGridViewTextBoxColumn userNameColumn = new DataGridViewTextBoxColumn();
            userNameColumn.Name = "colUserName";
            userNameColumn.HeaderText = toDoListCols[3];
            userNameColumn.Width = 80;
            userNameColumn.DataPropertyName = "USERNAME";
            this.dgvNotify.Columns.Add(userNameColumn);
            //REMARK
            DataGridViewTextBoxColumn remarkColumn = new DataGridViewTextBoxColumn();
            remarkColumn.Name = "colRemark";
            remarkColumn.HeaderText = toDoListCols[4];
            remarkColumn.Width = 120;
            remarkColumn.DataPropertyName = "REMARK";
            this.dgvNotify.Columns.Add(remarkColumn);
            //UPDATE_WHOLE_TIME
            DataGridViewTextBoxColumn updateWholeTimeColumn = new DataGridViewTextBoxColumn();
            updateWholeTimeColumn.Name = "colUpdateWholeTime";
            updateWholeTimeColumn.HeaderText = toDoListCols[5];
            updateWholeTimeColumn.Width = 120;
            updateWholeTimeColumn.DataPropertyName = "UPDATE_WHOLE_TIME";
            this.dgvNotify.Columns.Add(updateWholeTimeColumn);
            //STATUS
            DataGridViewTextBoxColumn statusColumn = new DataGridViewTextBoxColumn();
            statusColumn.Name = "colStatus";
            statusColumn.HeaderText = toDoListCols[6];
            statusColumn.Width = 80;
            statusColumn.DataPropertyName = "STATUS";
            this.dgvNotify.Columns.Add(statusColumn);
        }

        private void setOvertimeColumns()
        {
            string[] overtimeCols = SysMsg.GetSystemMessage(CliUtils.fClientLang, "EEPNetClient", "FrmClientMain", "OvertimeColumns").Split(',');
            //FLOW_DESC
            DataGridViewTextBoxColumn flDescColumn = new DataGridViewTextBoxColumn();
            flDescColumn.Name = "colFlDesc";
            flDescColumn.HeaderText = overtimeCols[0];
            flDescColumn.Width = 100;
            flDescColumn.DataPropertyName = "FLOW_DESC";
            this.dgvOvertime.Columns.Add(flDescColumn);
            //D_STEP_ID
            DataGridViewTextBoxColumn dStepIdColumn = new DataGridViewTextBoxColumn();
            dStepIdColumn.Name = "colDStepId";
            dStepIdColumn.HeaderText = overtimeCols[1];
            dStepIdColumn.Width = 80;
            dStepIdColumn.DataPropertyName = "D_STEP_ID";
            this.dgvOvertime.Columns.Add(dStepIdColumn);
            //FORM_PRESENTATION_CT
            DataGridViewTextBoxColumn formPresentationCtColumn = new DataGridViewTextBoxColumn();
            formPresentationCtColumn.Name = "colFormPresentationCT";
            formPresentationCtColumn.HeaderText = overtimeCols[2];
            formPresentationCtColumn.Width = 100;
            formPresentationCtColumn.DataPropertyName = "FORM_PRESENT_CT";
            this.dgvOvertime.Columns.Add(formPresentationCtColumn);
            //SENDTO_DETAIL
            DataGridViewTextBoxColumn sendToDetailColumn = new DataGridViewTextBoxColumn();
            sendToDetailColumn.Name = "colSendToDetail";
            sendToDetailColumn.HeaderText = overtimeCols[3];
            sendToDetailColumn.Width = 100;
            sendToDetailColumn.DataPropertyName = "SENDTO_DETAIL";
            this.dgvOvertime.Columns.Add(sendToDetailColumn);
            //REMARK
            DataGridViewTextBoxColumn remarkColumn = new DataGridViewTextBoxColumn();
            remarkColumn.Name = "colRemark";
            remarkColumn.HeaderText = overtimeCols[4];
            remarkColumn.Width = 100;
            remarkColumn.DataPropertyName = "REMARK";
            this.dgvOvertime.Columns.Add(remarkColumn);
            //UPDATE_WHOLE_TIME
            DataGridViewTextBoxColumn wholeTimeColumn = new DataGridViewTextBoxColumn();
            wholeTimeColumn.Name = "colWholeTime";
            wholeTimeColumn.HeaderText = overtimeCols[5];
            wholeTimeColumn.Width = 100;
            wholeTimeColumn.DataPropertyName = "UPDATE_WHOLE_TIME";
            this.dgvOvertime.Columns.Add(wholeTimeColumn);
            //OVERTIME
            DataGridViewTextBoxColumn overtimeColumn = new DataGridViewTextBoxColumn();
            overtimeColumn.Name = "colOvertime";
            overtimeColumn.HeaderText = overtimeCols[6];
            overtimeColumn.Width = 100;
            overtimeColumn.DataPropertyName = "OVERTIME";
            this.dgvOvertime.Columns.Add(overtimeColumn);
        }

        private void setToDoListOvertimeWarning()
        {
            foreach (DataGridViewRow dgvRow in this.dgvToDoList.Rows)
            {
                DataRowView row = (DataRowView)dgvRow.DataBoundItem;
                if (IsOverTime(row))
                {
                    DataGridViewCellStyle style = new DataGridViewCellStyle();
                    style.ForeColor = Color.Red;
                    dgvRow.DefaultCellStyle = style;
                }
            }
        }

        private void setNotifyOvertimeWarning()
        {
            foreach (DataGridViewRow dgvRow in this.dgvNotify.Rows)
            {
                DataRowView row = (DataRowView)dgvRow.DataBoundItem;
                if (IsOverTime(row))
                {
                    DataGridViewCellStyle style = new DataGridViewCellStyle();
                    style.ForeColor = Color.Red;
                    dgvRow.DefaultCellStyle = style;
                }
            }
        }

        private void setToDoHisOvertimeWarning()
        {
            foreach (DataGridViewRow dgvRow in this.dgvToDoHis.Rows)
            {
                DataRowView row = (DataRowView)dgvRow.DataBoundItem;
                if (IsOverTime(row))
                {
                    DataGridViewCellStyle style = new DataGridViewCellStyle();
                    style.ForeColor = Color.Red;
                    dgvRow.DefaultCellStyle = style;
                }
            }
        }

        private TimeSpan WorkTimeSpan(DateTime nowTime, DateTime updateTime, bool weekendSensible, List<string> extDates)
        {
            TimeSpan span = new TimeSpan();
            if (weekendSensible)
            {
                if (nowTime.DayOfWeek == DayOfWeek.Saturday)
                {
                    nowTime = nowTime.Date.AddSeconds(-1);
                }
                else if (nowTime.DayOfWeek == DayOfWeek.Sunday)
                {
                    nowTime = nowTime.Date.AddDays(-1).AddSeconds(-1);
                }

                if (updateTime.DayOfWeek == DayOfWeek.Saturday)
                {
                    updateTime = updateTime.Date.AddDays(2);
                }
                else if (updateTime.DayOfWeek == DayOfWeek.Sunday)
                {
                    updateTime = updateTime.Date.AddDays(1);
                }
            }
            span = nowTime - updateTime;
            if (weekendSensible)
            {
                int weekends = span.Days / 7;
                int i = nowTime.DayOfWeek - updateTime.DayOfWeek;
                if (i < 0)
                    weekends++;
                span = span.Subtract(new TimeSpan(2 * weekends, 0, 0, 0));
            }
            int extDays = 0;
            if (extDates == null) return span;
            foreach (string extDate in extDates)
            {
                if (Convert.ToDateTime(extDate).CompareTo(nowTime) < 0
                    && Convert.ToDateTime(extDate).CompareTo(updateTime) > 0)
                {
                    if (weekendSensible)
                    {
                        if (Convert.ToDateTime(extDate).DayOfWeek != DayOfWeek.Saturday
                            && Convert.ToDateTime(extDate).DayOfWeek != DayOfWeek.Sunday)
                        {
                            extDays++;
                        }
                    }
                    else
                    {
                        extDays++;
                    }
                }
            }
            span = span.Subtract(new TimeSpan(extDays, 0, 0, 0));
            return span;
        }

        private int lx;
        private int sx;
        bool flag = false;
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            if (flag == false)
            {
                lx = pictureBox1.Location.X;
                sx = this.scMaster.SplitterDistance;
                this.pictureBox1.Image = global::EEPNetFLClient.Properties.Resources.d1;
                this.pictureBox1.Location = new System.Drawing.Point(0, this.pictureBox1.Location.Y);                
                this.scMaster.SplitterDistance = this.pictureBox1.Size.Width;
                flag = true;
            }
            else
            {
                this.pictureBox1.Image = global::EEPNetFLClient.Properties.Resources.d2;
                this.pictureBox1.Location = new System.Drawing.Point(lx, this.pictureBox1.Location.Y);                
                if (sx <= 30) 
                    sx = 200;                
                this.scMaster.SplitterDistance = sx;
                flag = false;
            }
            this.Refresh();
        }

        private int locY;
        private int sizY;
        bool flag1 = false;
        private void pictureBox2_Click(object sender, EventArgs e)
        {
            if (flag1 == false)
            {
                locY = pictureBox2.Location.Y;
                sizY = panFLContainer.Size.Height;
                this.pictureBox2.Image = global::EEPNetFLClient.Properties.Resources.d3;
                this.pictureBox2.Location = new System.Drawing.Point(this.pictureBox2.Location.X, 0);
                this.panFLContainer.Size = new System.Drawing.Size(this.panFLContainer.Size.Width, this.pictureBox2.Height);
                flag1 = true;
            }
            else
            {
                this.pictureBox2.Image = global::EEPNetFLClient.Properties.Resources.d4;
                this.pictureBox2.Location = new System.Drawing.Point(this.pictureBox2.Location.X, locY);
                if (sizY <= 20) sizY = 200;
                this.panFLContainer.Size = new System.Drawing.Size(this.panFLContainer.Size.Width, sizY);
                flag1 = false;
            }
            this.Refresh();
        }

        private void lnkToDoListRefresh_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            this.wizToDoList.Refresh();
            this.setToDoListOvertimeWarning();
        }

        private void lnkToDoListQuery_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            this.panToDoListQuery.Visible = true;
        }

        private void chkSubmitted_CheckedChanged(object sender, EventArgs e)
        {
            if (this.chkSubmitted.Checked)
            {
                this.wizToDoHis.SqlMode = ESqlMode.FlowRunOver;
                this.wizToDoHis.Filter = "";
            }
            else
            {
                this.wizToDoHis.SqlMode = ESqlMode.ToDoHis;
                this.wizToDoHis.Filter = "";
            }
            this.wizToDoHis.Refresh();
            setToDoHistColumns();
            if (!this.chkSubmitted.Checked)
                setToDoHisOvertimeWarning();
        }

        private void lnkToDoHisRefresh_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            this.wizToDoHis.Refresh();
            if (this.wizToDoHis.SqlMode == ESqlMode.ToDoHis)
                this.setToDoHisOvertimeWarning();
        }

        private void lnkToDoHisQuery_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (!this.chkSubmitted.Checked)
            {
                this.panHisQuery.Visible = true;
                this.panHis2Query.Visible = false;
                this.chkSubmitted.Enabled = false;
            }
            else
            {
                this.panHis2Query.Visible = true;
                this.panHisQuery.Visible = false;
                this.chkSubmitted.Enabled = false;
            }
        }

        private void lnkNotifyRefresh_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            this.wizNotify.Refresh();
            this.setNotifyOvertimeWarning();
        }

        private void chkActive_CheckedChanged(object sender, EventArgs e)
        {
            GetOvertimeList();
        }

        private void GetOvertimeList()
        {
            if (this.chkActive.Checked)
            {
                this.wizOvertime.Refresh(this.cmbLevel.SelectedIndex, IgnoreWeekends, null);
            }
            else
            {
                this.dgvOvertime.DataSource = null;
            }
        }

        private void cmbLevel_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.chkActive.Checked)
            {
                object[] param = new object[5] { CliUtils.fLoginUser, this.cmbLevel.SelectedIndex, this.IgnoreWeekends, null, true };
                object[] obj = CliUtils.CallMethod("GLModule", "FLOvertimeList", param);
                if (obj!=null && Convert.ToInt16(obj[0]) == 0)
                {
                    DataTable tab = obj[1] as DataTable;
                    this.dgvOvertime.DataSource = tab;
                }
            }
            else
            {
                this.dgvOvertime.DataSource = null;
            }
        }

        private void lnkOvertimeRefresh_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {

        }

        bool solutionLoad = false;
        public void DoLoad()
        {
            DataSet dsSolution = new DataSet();
            if (CliUtils.fSolutionSecurity)
            {
                object[] myRet1 = CliUtils.CallMethod("GLModule", "GetSolutionSecurity", new object[] { CliUtils.fLoginUser, CliUtils.fGroupID });
                if ((null != myRet1) && (0 == (int)myRet1[0]))
                    dsSolution = ((DataSet)myRet1[1]);
            }
            else
            {
                object[] myRet1 = CliUtils.CallMethod("GLModule", "GetSolution", null);
                if ((null != myRet1) && (0 == (int)myRet1[0]))
                    dsSolution = ((DataSet)myRet1[1]);
            }
            this.infoCmbSolution.DataSource = dsSolution;
            string strTableName = dsSolution.Tables[0].TableName;
            this.infoCmbSolution.DisplayMember = strTableName + ".itemname";
            this.infoCmbSolution.ValueMember = strTableName + ".itemtype";
            int i = dsSolution.Tables[0].Rows.Count;
            for (int j = 0; j < i; j++)
            {
                if (string.Compare(dsSolution.Tables[0].Rows[j]["itemtype"].ToString(), CliUtils.fCurrentProject, true) == 0)//IgnoreCase
                {
                    this.infoCmbSolution.SelectedValue = dsSolution.Tables[0].Rows[j]["itemtype"].ToString();
                }
            }
            solutionLoad = true;
            bool flag = false;
            for (int x = 0; x < dsSolution.Tables[0].Rows.Count; x++)
            {
                if (CliUtils.fCurrentProject == dsSolution.Tables[0].Rows[x]["itemtype"].ToString())
                {
                    flag = true;
                    break;
                }
            }
            if (flag)
            {
                ItemToGet();
            }
        }

        private ArrayList MenuIDList = new ArrayList();
        private ArrayList CaptionList = new ArrayList();
        private ArrayList ParentList = new ArrayList();
        ArrayList ListMainID = new ArrayList();
        ArrayList ListMainCaption = new ArrayList();
        ArrayList ListChildrenID = new ArrayList();
        ArrayList ListOwnerParentID = new ArrayList();
        ArrayList ListChildrenCaption = new ArrayList();
        private ImageList IconList = new ImageList();

        private void ClearItems()
        {
            MenuIDList.Clear();
            CaptionList.Clear();
            ParentList.Clear();
            IconList.Images.Clear();
            ListMainID.Clear();
            ListMainCaption.Clear();
            ListChildrenID.Clear();
            ListOwnerParentID.Clear();
            ListChildrenCaption.Clear();            
            List<ToolStripItem> items = new List<ToolStripItem>();
            for (int i = 0; i < menuStrip1.Items.Count; i++)
            {
                if (menuStrip1.Items[i].Tag != null)
                {
                    items.Add(menuStrip1.Items[i]);
                }
            }
            for (int i = 0; i < items.Count; i++)
            {
                menuStrip1.Items.Remove(items[i]);
            }
        }

        private void ItemToGet()
        {
            ClearItems();
            if (this.infoCmbSolution.SelectedValue != null)
            {
                object[] LoginUser = new object[1];
                LoginUser[0] = CliUtils.fLoginUser;
                object[] strParam = new object[2];
                strParam[0] = this.infoCmbSolution.SelectedValue.ToString();
                strParam[1] = "F";

                string strCaption = SetMenuLanguage();

                object[] isTableExist = CliUtils.CallMethod("GLModule", "isTableExist", new object[] { "MENUFAVOR" });
                if (isTableExist != null && Convert.ToInt16(isTableExist[0]) == 0 && Convert.ToInt16(isTableExist[1]) == 0)
                {
                    object[] myRet1 = CliUtils.CallMethod("GLModule", "FetchFavorMenus", strParam);
                    if ((null != myRet1) && (0 == (int)myRet1[0]))
                    {
                        menuFavorDataSet = (DataSet)(myRet1[1]);
                        groupFavorDataSet = (DataSet)(myRet1[2]);
                    }
                    int menuFavorCount = menuFavorDataSet.Tables[0].Rows.Count;
                    if (menuFavorCount > 0)
                    {
                        SYS_LANGUAGE language = CliUtils.fClientLang;
                        String favor = SysMsg.GetSystemMessage(language, "EEPNetClient", "FavorMenu", "Favor");

                        MenuIDList.Add("MyFavor");
                        CaptionList.Add(favor);
                        ParentList.Add("");
                        IconList.Images.Add("MyFavor", imglst.Images[0]);

                        for (int i = 0; i < groupFavorDataSet.Tables[0].Rows.Count; i++)
                        {
                            if (groupFavorDataSet.Tables[0].Rows[i]["GROUPNAME"] != null && groupFavorDataSet.Tables[0].Rows[i]["GROUPNAME"].ToString() != "")
                            {
                                MenuIDList.Add(groupFavorDataSet.Tables[0].Rows[i]["GROUPNAME"].ToString());
                                CaptionList.Add(groupFavorDataSet.Tables[0].Rows[i]["GROUPNAME"].ToString());
                                ParentList.Add("MyFavor");
                            }
                        }

                        for (int i = 0; i < menuFavorCount; i++)
                        {
                            MenuIDList.Add(menuFavorDataSet.Tables[0].Rows[i]["MENUID"].ToString());
                            if (strCaption != "")
                            {
                                if (menuFavorDataSet.Tables[0].Rows[i][strCaption].ToString() != "")
                                    CaptionList.Add(menuFavorDataSet.Tables[0].Rows[i][strCaption].ToString());
                                else
                                    CaptionList.Add(menuFavorDataSet.Tables[0].Rows[i]["CAPTION"].ToString());
                            }
                            else
                            {
                                CaptionList.Add(menuFavorDataSet.Tables[0].Rows[i]["CAPTION"].ToString());
                            }

                            if (menuFavorDataSet.Tables[0].Rows[i]["GROUPNAME"] == null || menuFavorDataSet.Tables[0].Rows[i]["GROUPNAME"].ToString() == "")
                                ParentList.Add("MyFavor");
                            else
                                ParentList.Add(menuFavorDataSet.Tables[0].Rows[i]["GROUPNAME"].ToString());

                            //new add by ccm
                            try
                            {
                                byte[] blob = (byte[])menuFavorDataSet.Tables[0].Rows[i]["IMAGE"];

                                MemoryStream stmblob = new MemoryStream(blob);

                                try
                                {
                                    IconList.Images.Add(menuFavorDataSet.Tables[0].Rows[i]["MENUID"].ToString(), Image.FromStream(stmblob));
                                }
                                catch
                                {
                                    IconList.Images.Add(menuFavorDataSet.Tables[0].Rows[i]["MENUID"].ToString(), imglst.Images[0]);
                                }
                            }
                            catch
                            {
                                IconList.Images.Add(menuFavorDataSet.Tables[0].Rows[i]["MENUID"].ToString(), imglst.Images[0]);
                            }
                        }
                    }
                }

                object[] myRet = CliUtils.CallMethod("GLModule", "FetchMenus", strParam);
                if ((null != myRet) && (0 == (int)myRet[0]))
                {
                    menuDataSet = (DataSet)(myRet[1]);
                }
                int menuCount = menuDataSet.Tables[0].Rows.Count;
                for (int i = 0; i < menuCount; i++)
                {
                    MenuIDList.Add(menuDataSet.Tables[0].Rows[i]["MENUID"].ToString());
                    if (strCaption != "")
                    {
                        if (menuDataSet.Tables[0].Rows[i][strCaption].ToString() != "")
                            CaptionList.Add(menuDataSet.Tables[0].Rows[i][strCaption].ToString());
                        else
                            CaptionList.Add(menuDataSet.Tables[0].Rows[i]["CAPTION"].ToString());
                    }
                    else
                    {
                        CaptionList.Add(menuDataSet.Tables[0].Rows[i]["CAPTION"].ToString());
                    }
                    ParentList.Add(menuDataSet.Tables[0].Rows[i]["PARENT"].ToString());
                    //new add by ccm
                    try
                    {
                        byte[] blob = (byte[])menuDataSet.Tables[0].Rows[i]["IMAGE"];

                        MemoryStream stmblob = new MemoryStream(blob);

                        try
                        {
                            IconList.Images.Add(menuDataSet.Tables[0].Rows[i]["MENUID"].ToString(), Image.FromStream(stmblob));
                        }
                        catch
                        {
                            IconList.Images.Add(menuDataSet.Tables[0].Rows[i]["MENUID"].ToString(), imglst.Images[0]);
                        }
                    }
                    catch
                    {
                        IconList.Images.Add(menuDataSet.Tables[0].Rows[i]["MENUID"].ToString(), imglst.Images[0]);
                    }
                }


                for (int i = 0; i < MenuIDList.Count; i++)
                {
                    if (ParentList[i].ToString().Length == 0)
                    {
                        ListMainID.Add(MenuIDList[i].ToString());
                        ListMainCaption.Add(CaptionList[i].ToString());
                    }
                    else
                    {
                        ListChildrenID.Add(MenuIDList[i].ToString());
                        ListOwnerParentID.Add(ParentList[i].ToString());
                        ListChildrenCaption.Add(CaptionList[i].ToString());
                    }
                }
                IconList.Images.Add("MyFavor~1", imglst.Images[1]);
                IconList.Images.Add("MyFavor~2", imglst.Images[2]);                
                initializeMenu();
                initializeTreeView();
            }
        }

        private string SetMenuLanguage()
        {
            string strCaption = "";
            switch (Startup.GetClientLanguage())
            {
                case SYS_LANGUAGE.ENG:
                    strCaption = "CAPTION0";
                    break;
                case SYS_LANGUAGE.TRA:
                    strCaption = "CAPTION1";
                    break;
                case SYS_LANGUAGE.SIM:
                    strCaption = "CAPTION2";
                    break;
                case SYS_LANGUAGE.HKG:
                    strCaption = "CAPTION3";
                    break;
                case SYS_LANGUAGE.JPN:
                    strCaption = "CAPTION4";
                    break;
                case SYS_LANGUAGE.LAN1:
                    strCaption = "CAPTION5";
                    break;
                case SYS_LANGUAGE.LAN2:
                    strCaption = "CAPTION6";
                    break;
                case SYS_LANGUAGE.LAN3:
                    strCaption = "CAPTION7";
                    break;
            }
            return strCaption;
        }

        private void initializeMenu()
        {
            for (int i = 0; i < ListMainID.Count; i++)
            {
                ToolStripMenuItem item = new ToolStripMenuItem();
                item.Text = ListMainCaption[i].ToString();                
                item.Tag = ListMainID[i].ToString();                
                this.menuStrip1.Items.Insert(this.menuStrip1.Items.Count - 2, item);
            }

            List<ToolStripItem> emptyItems = new List<ToolStripItem>();

            for (int i = 0; i < menuStrip1.Items.Count; i++)
            {
                if (menuStrip1.Items[i].Tag != null)
                {
                    InitializeItem((ToolStripMenuItem)menuStrip1.Items[i]);
                    if (IsEmptyFolderItem((ToolStripMenuItem)menuStrip1.Items[i]))
                    {
                        emptyItems.Add(menuStrip1.Items[i]);
                    }
                }
            }
            foreach (ToolStripMenuItem item in emptyItems)
            {
                menuStrip1.Items.Remove(item);
            }
        }

        private bool IsEmptyFolderItem(ToolStripMenuItem item)
        {
            if (item != null && item.DropDownItems.Count == 0)
            {
                if (item.Tag != null)
                {
                    DataRow[] dr = menuDataSet.Tables[0].Select(string.Format("MENUID='{0}'", item.Tag));
                    if (dr.Length > 0)
                    {
                        return (dr[0]["PACKAGE"] == DBNull.Value || dr[0]["PACKAGE"].ToString().Length == 0);
                    }
                }
            }
            return false;
        }

        private void InitializeItem(ToolStripMenuItem item)
        {
            for (int i = 0; i < ListChildrenID.Count; i++)
            {
                if (item.Tag.ToString() == ListOwnerParentID[i].ToString())
                {
                    ToolStripMenuItem itemChild = new ToolStripMenuItem();
                    itemChild.Text = ListChildrenCaption[i].ToString();
                    itemChild.Image = IconList.Images[ListChildrenID[i].ToString()];
                    itemChild.Tag = ListChildrenID[i].ToString();
                    itemChild.Click += new EventHandler(menu_Click);
                    if (IsEmptyWithPackage(itemChild.Tag.ToString()))
                    {
                        itemChild.Image = IconList.Images["MyFavor~1"];                        
                    }
                    item.DropDownItems.Add(itemChild);
                }
            }

            for (int i = 0; i < item.DropDownItems.Count; i++)
            {
                InitializeItem((ToolStripMenuItem)item.DropDownItems[i]);
            }
        }

        private void menu_Click(object sender, EventArgs e)
        {
            try
            {
                string strText = ((ToolStripMenuItem)sender).Tag.ToString();
                showForm(strText, ((ToolStripMenuItem)sender).Text);
            }
            catch (Exception ex)
            {
                frmWaiting.CloseWaiting();
                string error = ex.Message + "\r\n\r\n";
                if (ex.InnerException != null)
                    error += ex.InnerException.Message;
                MessageBox.Show(error, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void initializeTreeView()
        {           
            Ascend.Windows.Forms.NavigationPanePage oea = null;
            TreeView tv;
            for (int i = 0; i < ListMainID.Count; i++)
            {
                oea = new Ascend.Windows.Forms.NavigationPanePage();
                oea.Name = ListMainID[i].ToString();
                oea.Text = ListMainCaption[i].ToString();
                oea.Image = IconList.Images[ListMainID[i].ToString()];
                tv = new TreeView();
                tv.Dock = DockStyle.Fill;
                tv.ImageList = IconList;
                tv.NodeMouseDoubleClick += new TreeNodeMouseClickEventHandler(tView_NodeMouseDoubleClick);
                tv.Name = ListMainID[i].ToString();
                for (int j = 0; j < ListChildrenID.Count; j++)
                {
                    if (tv.Name.ToString() == ListOwnerParentID[j].ToString())
                    {
                        TreeNode nodeChild = new TreeNode();
                        nodeChild.Text = ListChildrenCaption[j].ToString();
                        nodeChild.SelectedImageKey = ListChildrenID[j].ToString();                        
                        nodeChild.ImageKey = ListChildrenID[j].ToString();
                        nodeChild.Tag = ListChildrenID[j].ToString();
                        nodeChild.Name = nodeChild.Tag.ToString();
                        if (IsEmptyWithPackage(nodeChild.Tag.ToString()))
                        {
                            nodeChild.ImageKey = "MyFavor~1";
                            nodeChild.SelectedImageKey = "MyFavor~2";
                        }
                        InitializeNode(nodeChild);
                        tv.Nodes.Add(nodeChild);
                    }
                }                
                tv.ExpandAll();
                if (tv.Nodes.Count > 0)
                {
                    oea.Controls.Add(tv);
                    this.onavMaster.NavigationPages.Add(oea);
                }                
            }
        }

        private bool IsEmptyWithPackage(string id)
        {
            DataRow[] dr = menuDataSet.Tables[0].Select(string.Format("MENUID='{0}'", id));
            if (dr.Length > 0)
            {
                return (dr[0]["PACKAGE"] == DBNull.Value || dr[0]["PACKAGE"].ToString().Length == 0);
            }
            return false;
        }

        private bool IsEmptyFolderNode(TreeNode node)
        {
            if (node != null && node.Nodes.Count == 0)
            {
                if (node.Tag != null)
                {
                    DataRow[] dr = menuDataSet.Tables[0].Select(string.Format("MENUID='{0}'", node.Tag));
                    if (dr.Length > 0)
                    {
                        return (dr[0]["PACKAGE"] == DBNull.Value || dr[0]["PACKAGE"].ToString().Length == 0);
                    }
                }
            }
            return false;
        }

        private void InitializeNode(TreeNode node)
        {
            for (int i = 0; i < ListChildrenID.Count; i++)
            {
                if (node.Name == ListOwnerParentID[i].ToString())
                {
                    TreeNode nodeChild = new TreeNode();
                    nodeChild.Text = ListChildrenCaption[i].ToString();
                    nodeChild.SelectedImageKey = ListChildrenID[i].ToString();
                    nodeChild.ImageKey = ListChildrenID[i].ToString();
                    nodeChild.Tag = ListChildrenID[i].ToString();
                    nodeChild.Name = nodeChild.Tag.ToString();
                    if (IsEmptyWithPackage(nodeChild.Tag.ToString()))
                    {
                        nodeChild.ImageKey = "MyFavor~1";
                        nodeChild.SelectedImageKey = "MyFavor~2";
                    }
                    node.Nodes.Add(nodeChild);
                }
            }

            for (int i = 0; i < node.Nodes.Count; i++)
            {
                InitializeNode(node.Nodes[i]);
            }            
        }

        private void infoCmbSolution_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (solutionLoad)
            {
                int length = this.MdiChildren.Length;
                for (int i = 0; i < length; i++)
                {
                    this.MdiChildren[0].Close();
                    if (i + MdiChildren.Length >= length)
                    {
                        cmbSolution.SelectedIndexChanged -= new EventHandler(infoCmbSolution_SelectedIndexChanged);
                        this.cmbSolution.SelectedValue = CliUtils.fCurrentProject;//设回原来的solution
                        cmbSolution.SelectedIndexChanged += new EventHandler(infoCmbSolution_SelectedIndexChanged);
                        return;
                    }
                }
                ItemToGet();
                if (this.cmbSolution.SelectedValue == null)
                    CliUtils.fCurrentProject = "";
                else
                    CliUtils.fCurrentProject = this.cmbSolution.SelectedValue.ToString();
            }
        }

        public ComboBox cmbSolution
        {
            get
            {
                return this.infoCmbSolution;
            }
        }

        private void tView_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            TreeView tv = sender as TreeView;
            Ascend.Windows.Forms.NavigationPanePage npp = tv.Parent as Ascend.Windows.Forms.NavigationPanePage;
            EEPNetFLClient.Properties.Settings.Default.LastClick = this.onavMaster.NavigationPages.IndexOf(npp).ToString() + 
                "|" + tv.Name + "|" + tv.SelectedNode.Name; //便于下次登录定位   
            try
            {
                if (tv.SelectedNode != null)
                {
                    int ChildrenNum = tv.SelectedNode.GetNodeCount(true);
                    if (ChildrenNum == 0)
                    {
                        string strText = ((TreeView)sender).SelectedNode.Tag.ToString();
                        showForm(strText, ((TreeView)sender).SelectedNode.Text);
                    }
                }
            }
            catch (Exception ex)
            {
                frmWaiting.CloseWaiting();
                string error = ex.Message+"\r\n\r\n";
                if (ex.InnerException!=null)
                    error+=ex.InnerException.Message;
                MessageBox.Show(error, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        System.Collections.Specialized.NameValueCollection _nvMenuId = new NameValueCollection();
        System.Collections.Specialized.NameValueCollection _nvMenuKey = new NameValueCollection();
        public void showForm(string PackageName, string FormName, string ItemParam, StringDictionary FLParams)
        {
            string menuid = "";
            if (String.IsNullOrEmpty(ItemParam))
                ItemParam = "";
            string key = PackageName.ToLower() + "~" + FormName.ToLower() + "~" + ItemParam.ToLower();            
            menuid = _nvMenuId.Get(key);
            if (String.IsNullOrEmpty(menuid))
            {
                menuid = Guid.NewGuid().ToString();
                _nvMenuId.Add(key, menuid);
                _nvMenuKey.Add(menuid,key);
            }
            showForm(menuid, "", PackageName, FormName, ItemParam, "", FLParams);
        }

        private void showForm(string id, string text)
        {
            string PackageName = "";
            string FormName = "";
            string ItemParam = "";
            string ModuleType = "";
            int i = menuDataSet.Tables[0].Rows.Count;
            for (int j = 0; j < i; j++)
            {
                if (id == menuDataSet.Tables[0].Rows[j]["MENUID"].ToString())
                {
                    PackageName = menuDataSet.Tables[0].Rows[j]["PACKAGE"].ToString();
                    FormName = menuDataSet.Tables[0].Rows[j]["FORM"].ToString();
                    ItemParam = menuDataSet.Tables[0].Rows[j]["ITEMPARAM"].ToString();
                    ModuleType = menuDataSet.Tables[0].Rows[j]["moduletype"].ToString();
                    break;
                }
            }
            
            if (PackageName=="" && FormName=="" && ItemParam=="")
            {
                string _str = _nvMenuKey.Get(id); ;
                
                if (!String.IsNullOrEmpty(_str))
                {
                    string[] _strs = _str.Split('~');
                    PackageName = _strs[0];
                    FormName = _strs[1];
                    ItemParam = _strs[2];
                }
            }
            showForm(id,text,PackageName, FormName, ItemParam, ModuleType, null);
        }

        public void showForm(string id, string text,string PackageName, string FormName, string ItemParam, string ModuleType, StringDictionary FLParams)
        {            
            if (PackageName == "")            
                return;            
            try
            {                
                FormItem f = fFormCollection.FindFormItem(PackageName, FormName);
                if ((null != f) && (!f.MultiInstance))
                {
                    Type t = f.oInfoForm.GetType();
                    if (t.Namespace == f.PackageName && f.oInfoForm.Name == f.FormName)
                    {
                        f.oInfoForm.Show();
                        if (f.oInfoForm.WindowState == FormWindowState.Minimized)
                        {
                            f.oInfoForm.WindowState = FormWindowState.Normal;
                        }
                        f.oInfoForm.Activate();                        
                    }
                    else if (t.Namespace.ToLower() == "eepnetflclient" && f.oInfoForm.Name.ToLower() == "flowdesingerform")
                    {                        
                        this.panel7.Controls.Clear();
                        this.panel7.Controls.Add(f.oInfoForm);
                        f.oInfoForm.Show();
                        f.oInfoForm.Activate();                        
                    }
                    return;                 //如果已经有对象，并且不许多个，则退出
                }               
                if (ModuleType == "O")
                {
                    string path = PackageName + "\\" + FormName + ".xoml";
                    object[] objs = CliUtils.CallFLMethod("GetFLDefinitionXmlString", new object[] { path });
                    if (objs[0] != null && (int)objs[0] == 0)
                    {
                        string xml = objs[1] as string;
                        byte[] bytes = System.Text.Encoding.UTF8.GetBytes(xml);
                        MemoryStream stream = new MemoryStream(bytes);

                        FLowDesingerForm flDesingerForm = new FLowDesingerForm(this, stream);
                        string ffn = CliUtils.CallFLMethod("GetFLServerPath", new object[] { path })[1].ToString();
                        flDesingerForm.FlowFileName = ffn;                        
                        flDesingerForm.TopLevel = false;
                        flDesingerForm.FormBorderStyle = FormBorderStyle.None;
                        flDesingerForm.Dock = DockStyle.Fill;
                        flDesingerForm.MinimizeBox = false;
                        flDesingerForm.MaximizeBox = false;
                        flDesingerForm.Text = text;
                        flDesingerForm.FormClosed += InternalFormClosed;
                        flDesingerForm.Tag = id;

                        this.panel7.Controls.Clear();
                        this.panel7.Controls.Add(flDesingerForm);

                        ((IInfoForm)flDesingerForm).SetPackageForm(PackageName, FormName);
                        fFormCollection.AddPackageForm(PackageName, FormName, flDesingerForm).MultiInstance = ((IInfoForm)flDesingerForm).GetMultiInstance();
                        ((Form)flDesingerForm).FormClosed += InternalFormClosed;

                        frmWaiting.CloseWaiting();
                        flDesingerForm.Show();
                        return;
                    }
                }

                String s;
                s = Application.StartupPath + "\\" + CliUtils.fCurrentProject + "\\";

                string strPackage = s + PackageName + ".dll";
                Assembly a = null;
                bool bLoaded = DllContainer.DllLoaded(strPackage);

                if (!bLoaded || !File.Exists(strPackage)) CheckAndDownLoad(strPackage, PackageName + ".dll");
                try
                {
                    a = Assembly.LoadFrom(strPackage);
                }
                finally
                {
                    if (!bLoaded) 
                        DllContainer.AddDll(strPackage);
                }

                Type myType = a.GetType(PackageName + "." + FormName);
                if (myType != null)
                {
                    object obj = Activator.CreateInstance(myType);
                    IInfoForm _iInfoForm = obj as IInfoForm;
                    InfoForm _form = obj as InfoForm;

                    _iInfoForm.SetPackageForm(PackageName, FormName);
                    if (_form.ShowMenuText && text!="")
                    {
                        _form.Text = text;
                    }
                    _form.Tag = id;
                    fFormCollection.AddPackageForm(PackageName, FormName, _form).MultiInstance = _iInfoForm.GetMultiInstance();
                    _form.FormClosed += InternalFormClosed;
                    if (FLParams != null && FLParams is StringDictionary)
                    {
                        _form.fLItemParamters = FLParams as StringDictionary;
                    }
                    _form.ItemParamters = ItemParam;                    
                    _form.Owner = this;

                    _form.Load += new EventHandler(_form_Load);
                    _form.StartPosition = FormStartPosition.CenterScreen;
                    _form.Show();
                    if (_form.WindowState == FormWindowState.Maximized)
                    {
                        _form.Hide();
                        _form.WindowState = FormWindowState.Normal;
                        _form.WindowState = FormWindowState.Maximized;
                        _form.Show();
                    }
                }
                else
                {
                    MessageBox.Show(string.Format("Form: {0} doesn't exist", FormName));
                }
            }
            catch (Exception ex)
            {
                frmWaiting.CloseWaiting();
                string errMsg = ex.Message;
                if (ex.InnerException != null)
                    errMsg += "\r\n\r\n" + ex.InnerException.Message;
                MessageBox.Show("打开窗体发生错误:\r\n\r\n" + errMsg, "错误提示");
            }            
        }

        void _form_Load(object sender, EventArgs e)
        {
            frmWaiting.CloseWaiting();   
        }
       
        private void InternalFormClosed(object sender, FormClosedEventArgs e)
        {
            IInfoForm aForm = (IInfoForm)sender;
            fFormCollection.RemovePackageForm(aForm.GetPackageName(), aForm.GetFormName());
        }

        public class FormItem : InfoOwnerCollectionItem
        {
            private string fPackageName = "";
            public string PackageName
            {
                get
                {
                    return fPackageName;
                }
                set
                {
                    fPackageName = value;
                }
            }

            private string fFormName = "";
            public string FormName
            {
                get
                {
                    return fFormName;
                }
                set
                {
                    fFormName = value;
                }
            }

            public override string Name
            {
                get
                {
                    return fPackageName + "." + fFormName;
                }
                set
                {
                    int iPos = value.IndexOf('.');
                    if (-1 != iPos)
                    {
                        fPackageName = value.Substring(0, iPos);
                        fFormName = value.Substring(iPos + 1);
                    }
                }
            }

            private bool fMultiInstance = false;
            public bool MultiInstance
            {
                get
                {
                    return fMultiInstance;
                }
                set
                {
                    fMultiInstance = value;
                }
            }

            private int fCount = 0;
            public int Count
            {
                get
                {
                    return fCount;
                }
                set
                {
                    fCount = value;
                }
            }

            private InfoForm fInfoForm = null;
            public InfoForm oInfoForm
            {
                get
                {
                    return fInfoForm;
                }
                set
                {
                    fInfoForm = value;
                }
            }
        }

        public class FormCollection : InfoOwnerCollection
        {
            public FormCollection(Component aOwner, Type aItemType)
                : base(aOwner, typeof(FormItem))
            {

            }

            new public FormItem this[int index]
            {
                get
                {
                    return (FormItem)InnerList[index];
                }
                set
                {
                    if (index > -1 && index < Count)
                        if (value is FormItem)
                        {
                            //原来的Collection设置为0
                            ((FormItem)InnerList[index]).Collection = null;
                            InnerList[index] = value;
                            //Collection设置为this
                            ((FormItem)InnerList[index]).Collection = this;
                        }
                }
            }

            public FormItem FindFormItem(string pkg, string frm)
            {
                FormItem fRet = null;
                foreach (FormItem f in this)
                {
                    if (string.Compare(f.PackageName, pkg, true) == 0 && string.Compare(f.FormName, frm, true) == 0)//IgnoreCase
                    {
                        fRet = f;
                        break;
                    }
                }
                return fRet;
            }

            public FormItem AddPackageForm(string pkg, string frm, object obj)
            {
                FormItem fRet = FindFormItem(pkg, frm);

                if (null == fRet)
                {
                    InfoForm _infoForm = obj as InfoForm;
                    fRet = new FormItem();
                    fRet.PackageName = pkg; fRet.FormName = frm;
                    fRet.oInfoForm = _infoForm;
                    this.Add(fRet);
                    frmClientFL _frmClientFL = this.Owner as frmClientFL;
                    ToolStripMenuItem _mi = new ToolStripMenuItem();
                    _mi.Text = _infoForm.Text;
                    _mi.Tag = _infoForm.Tag;
                    _mi.Click += new EventHandler(_frmClientFL.menu_Click);
                    _frmClientFL.windowsToolStripMenuItem.DropDownItems.Insert(_frmClientFL.windowsToolStripMenuItem.DropDownItems.Count-2,_mi);
                    _frmClientFL.windowsToolStripMenuItem.Enabled = _frmClientFL.windowsToolStripMenuItem.DropDownItems.Count > 2;
                }

                fRet.Count++;
                return fRet;
            }

            public void RemovePackageForm(string pkg, string frm)
            {                
                FormItem fRet = FindFormItem(pkg, frm);               
                if (null != fRet)
                {
                    frmClientFL _frmClientFL = this.Owner as frmClientFL;
                    foreach (ToolStripItem mi in _frmClientFL.windowsToolStripMenuItem.DropDownItems)
                    {
                        ToolStripMenuItem _mi = mi as ToolStripMenuItem;

                        if (mi.Tag == null || _mi == null)
                            continue;
                        if (mi.Tag.ToString().ToLower() == fRet.oInfoForm.Tag.ToString().ToLower())
                        {
                            _frmClientFL.windowsToolStripMenuItem.DropDownItems.Remove(mi);
                            break;
                        }
                    }
                    _frmClientFL.windowsToolStripMenuItem.Enabled = _frmClientFL.windowsToolStripMenuItem.DropDownItems.Count > 2;

                    fRet.Count--;
                    if (fRet.Count == 0)
                        this.Remove(fRet);
                }
            }

            /// <summary>
            /// 隐藏所有子窗体
            /// </summary>
            public void HidePackageForm()
            {
                foreach (FormItem f in this)
                {
                    if (f.oInfoForm.Name.ToLower() == "flowdesingerform")
                        f.oInfoForm.WindowState = FormWindowState.Maximized;
                }
            }

            /// <summary>
            /// 关闭所有子窗体
            /// </summary>
            public void ClosePackageForm()
            {
                FormItem fRet;
                for (int i = this.Count - 1; i >= 0; i--)
                {
                    fRet=this[i];
                    RemovePackageForm((fRet.oInfoForm as IInfoForm).GetPackageName(),(fRet.oInfoForm as IInfoForm).GetFormName());
                    fRet.oInfoForm.Close();
                    fRet.oInfoForm.Dispose();
                }
            }
        }

        void frmClientFL_Activated(object sender, EventArgs e)
        {            
            fFormCollection.HidePackageForm();            
        }

        private void frmClientFL_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.fFormCollection.ClosePackageForm();
            if (CliUtils.fLoginUser.Length > 0)
            {
                if (!CliUtils.closeProtected)
                    CliUtils.CallMethod("GLModule", "LogOut", new object[] { (object)(CliUtils.fLoginUser) });
            }            
        }

        private void wmiCloseAll_Click(object sender, EventArgs e)
        {
            this.fFormCollection.ClosePackageForm();
            this.panel7.Controls.Clear();
        }

        protected override void OnResize(EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                foreach (Form f in Application.OpenForms)
                {
                    if (f != this)
                    {
                        if (f.ShowInTaskbar)
                        {
                            f.WindowState = FormWindowState.Minimized;
                        }
                    }
                }
            }
            base.OnResize(e);
        }

        private void CheckAndDownLoad(string sFullPath, string sDll)
        {
            object[] oRet = null;
            DateTime d = File.GetLastWriteTime(sFullPath);//取得最后时间

            System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(ShowProgressBar));
            t.Start();
            try
            {
                oRet = CliUtils.CallMethod("GLModule", "CheckAndDownLoadCompressed", new object[] { CliUtils.fCurrentProject, sDll, d, true });
            }
            finally
            {
                bAbort = true;
                t.Join();
            }

            if (null != oRet && ((int)oRet[0] == 0) && ((int)oRet[1] == 0))
            {
                byte[] bs = (byte[])oRet[3];
                //数据解压缩
                MemoryStream sourceStream = null;
                GZipStream decompressedStream = null;
                byte[] quartetBuffer = null;
                byte[] buffer = null;

                try
                {
                    sourceStream = new MemoryStream();
                    sourceStream.Write(bs, 0, bs.Length);
                    // Create a compression stream pointing to the destiantion stream
                    decompressedStream = new GZipStream(sourceStream, CompressionMode.Decompress, true);

                    // Read the footer to determine the length of the destiantion file
                    quartetBuffer = new byte[4];
                    int position = (int)sourceStream.Length - 4;
                    sourceStream.Position = position;
                    sourceStream.Read(quartetBuffer, 0, 4);
                    sourceStream.Position = 0;
                    int checkLength = BitConverter.ToInt32(quartetBuffer, 0);

                    buffer = new byte[checkLength + 100];

                    int offset = 0;
                    int total = 0;

                    // Read the compressed data into the buffer
                    while (true)
                    {
                        int bytesRead = decompressedStream.Read(buffer, offset, 100);

                        if (bytesRead == 0)
                            break;

                        offset += bytesRead;
                        total += bytesRead;
                    }


                }
                catch (ApplicationException ex)
                {

                    MessageBox.Show(ex.Message, "解压文件时发生错误：", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    // Make sure we allways close all streams
                    if (sourceStream != null) sourceStream.Close();

                    if (decompressedStream != null) decompressedStream.Close();

                }
                //解压结束

                DateTime ds = (DateTime)oRet[2];
                string sPath = Path.GetDirectoryName(sFullPath);
                if (!Directory.Exists(sPath))
                    Directory.CreateDirectory(sPath);
                File.WriteAllBytes(sFullPath, buffer); //bs
                File.SetLastWriteTime(sFullPath, ds);
            }
        }

        private bool bAbort = false;
        private void ShowProgressBar()
        {
            ProgressForm aForm = new ProgressForm();
            aForm.Show();
            while (!bAbort || aForm.progressBar1.Value < 99)
            {
                if (aForm.progressBar1.Value + 3 > 100)
                {
                    aForm.progressBar1.Value = 1;
                }
                else
                {
                    aForm.progressBar1.Value += 3;
                }
                System.Threading.Thread.Sleep(5);
            }
        }

        const String oracleDateFormat = "'yyyy/MM/dd hh24:mi:ss'";
        const String informixDateFormat = "'%Y%m%d%H%M%S'";
        private void btnLstQueryOK_Click(object sender, EventArgs e)
        {
            String connectMark = "+";
            String DBAlias = CliUtils.fLoginDB;
            object[] myRet = CliUtils.CallMethod("GLModule", "GetDataBaseType", new object[] { DBAlias });
            if (myRet != null && myRet[0].ToString() == "0")
            {
                switch (myRet[1].ToString())
                {
                    case "1": connectMark = "+"; break;
                    case "2": connectMark = "+"; break;
                    case "3": connectMark = "||"; break;
                    case "4": connectMark = "||"; break;
                    case "5": connectMark = "||"; break;
                    case "6": connectMark = "||"; break;
                }
            }

            string filter = "";
            if (this.cmbLstFlow.SelectedIndex > 0)
            {
                filter += "SYS_TODOLIST.FLOW_DESC='" + this.cmbLstFlow.Text + "' AND ";
            }
            if (!string.IsNullOrEmpty(this.txtLstDstep.Text))
            {
                filter += "SYS_TODOLIST.D_STEP_ID LIKE '" + this.txtLstDstep.Text + "%' AND ";
            }
            if (this.cmbLstUser.SelectedIndex > 0)
            {
                filter += "SYS_TODOLIST.USERNAME='" + this.cmbLstUser.Text + "' AND ";
            }
            if (!string.IsNullOrEmpty(this.txtLstFormPresent.Text))
            {
                filter += "SYS_TODOLIST.FORM_PRESENT_CT LIKE '%" + this.txtLstFormPresent.Text + "%' AND ";
            }
            if (this.dtpLstDateFrom.Checked)
            {
                if (myRet != null && myRet[0].ToString() == "0")
                {
                    switch (myRet[1].ToString())
                    {
                        case "1":
                            filter += "CAST((SYS_TODOLIST.UPDATE_DATE " + connectMark + " ' ' " + connectMark + " SYS_TODOLIST.UPDATE_TIME) AS DATETIME) > '" + this.dtpLstDateFrom.Value.ToShortDateString() + "' AND ";
                            break;
                        case "2":
                            filter += "((SYS_TODOLIST.UPDATE_DATE " + connectMark + " ' ' " + connectMark + " SYS_TODOLIST.UPDATE_TIME) AS DATETIME) > '" + this.dtpLstDateFrom.Value.ToShortDateString() + "' AND ";
                            break;
                        case "3":
                            filter += "to_date(SYS_TODOLIST.UPDATE_DATE " + connectMark + " ' ' " + connectMark + " SYS_TODOLIST.UPDATE_TIME, " + oracleDateFormat + ") > to_date('" + this.dtpLstDateFrom.Value.ToShortDateString() + "', " + oracleDateFormat + ") AND ";
                            break;
                        case "4":
                            filter += string.Format("to_date(SYS_TODOLIST.UPDATE_DATE {0} ' ' {0} SYS_TODOLIST.UPDATE_TIME, {1}) > to_date('{2}', {1})  AND ", connectMark, informixDateFormat, this.dtpLstDateFrom.Value.ToShortDateString());
                            break;
                        case "5":
                            filter += string.Format("CONCAT(SYS_TODOLIST.UPDATE_DATE, ' ', SYS_TODOLIST.UPDATE_TIME) > '{0}'  AND ", this.dtpLstDateFrom.Value.ToShortDateString());
                            break;
                        case "6":
                            filter += string.Format("to_date(SYS_TODOLIST.UPDATE_DATE {0} ' ' {0} SYS_TODOLIST.UPDATE_TIME, {1}) > to_date('{2}', {1})  AND ", connectMark, informixDateFormat, this.dtpLstDateFrom.Value.ToShortDateString());
                            break;
                    }
                }
            }
            if (this.dtpLstDateTo.Checked)
            {
                if (myRet != null && myRet[0].ToString() == "0")
                {
                    switch (myRet[1].ToString())
                    {
                        case "1":
                            filter += "CAST((SYS_TODOLIST.UPDATE_DATE " + connectMark + " ' ' " + connectMark + " SYS_TODOLIST.UPDATE_TIME) AS DATETIME) < '" + this.dtpLstDateTo.Value.ToShortDateString() + " 23:59:59' AND ";
                            break;
                        case "2":
                            filter += "((SYS_TODOLIST.UPDATE_DATE " + connectMark + " ' ' " + connectMark + " SYS_TODOLIST.UPDATE_TIME) AS DATETIME) < '" + this.dtpLstDateTo.Value.ToShortDateString() + " 23:59:59' AND ";
                            break;
                        case "3":
                            filter += "to_date(SYS_TODOLIST.UPDATE_DATE " + connectMark + " ' ' " + connectMark + " SYS_TODOLIST.UPDATE_TIME, " + oracleDateFormat + ") < to_date('" + this.dtpLstDateTo.Value.ToShortDateString() + " 23:59:59', " + oracleDateFormat + ") AND ";
                            break;
                        case "4":
                            filter += string.Format("to_date(SYS_TODOLIST.UPDATE_DATE {0} ' ' {0} SYS_TODOLIST.UPDATE_TIME, {1}) < to_date('{2}', {1})  AND ", connectMark, informixDateFormat, this.dtpLstDateTo.Value.ToShortDateString() + " 23:59:59");
                            break;
                        case "5":
                            filter += "CONCAT(SYS_TODOLIST.UPDATE_DATE, ' ', SYS_TODOLIST.UPDATE_TIME) < '" + this.dtpLstDateTo.Value.ToShortDateString() + " 23:59:59' AND ";
                            break;
                        case "6":
                            filter += string.Format("to_date(SYS_TODOLIST.UPDATE_DATE {0} ' ' {0} SYS_TODOLIST.UPDATE_TIME, {1}) < to_date('{2}', {1})  AND ", connectMark, informixDateFormat, this.dtpLstDateTo.Value.ToShortDateString() + " 23:59:59");
                            break;
                    }
                }
            }
            if (!string.IsNullOrEmpty(this.txtLstRemark.Text))
            {
                filter += "SYS_TODOLIST.REMARK LIKE '%" + this.txtLstRemark.Text + "%' AND ";
            }

            if (!string.IsNullOrEmpty(filter))
            {
                filter = filter.Substring(0, filter.LastIndexOf(" AND "));
            }

            this.wizToDoList.Refresh(filter);

            this.panToDoListQuery.Visible = false;
        }

        private void btnLstQueryCancel_Click(object sender, EventArgs e)
        {
            this.panToDoListQuery.Visible = false;
        }

        private void btnHis2QueryOK_Click(object sender, EventArgs e)
        {
            String connectMark = "+";
            String DBAlias = CliUtils.fLoginDB;
            object[] myRet = CliUtils.CallMethod("GLModule", "GetDataBaseType", new object[] { DBAlias });
            if (myRet != null && myRet[0].ToString() == "0")
            {
                switch (myRet[1].ToString())
                {
                    case "1": connectMark = "+"; break;
                    case "2": connectMark = "+"; break;
                    case "3": connectMark = "||"; break;
                    case "4": connectMark = "||"; break;
                    case "5": connectMark = "||"; break;
                    case "6": connectMark = "||"; break;
                }
            }

            string filter = "";
            if (this.cmbHis2Flow.SelectedIndex > 0)
            {
                filter += "SYS_TODOHIS.FLOW_DESC='" + this.cmbHis2Flow.Text + "' AND ";
            }
            if (!string.IsNullOrEmpty(this.txtHis2DStep.Text))
            {
                filter += "SYS_TODOHIS.D_STEP_ID LIKE '" + this.txtHis2DStep.Text + "%' AND ";
            }
            if (!string.IsNullOrEmpty(this.txtHis2FormPresent.Text))
            {
                filter += "SYS_TODOHIS.FORM_PRESENT_CT LIKE '%'" + this.txtHis2FormPresent.Text + "%' AND ";
            }
            if (this.dtpHis2DateFrom.Checked)
            {
                if (myRet != null && myRet[0].ToString() == "0")
                {
                    switch (myRet[1].ToString())
                    {
                        case "1":
                            filter += "CAST((SYS_TODOHIS.UPDATE_DATE " + connectMark + " ' ' " + connectMark + " SYS_TODOHIS.UPDATE_TIME) AS DATETIME) > '" + this.dtpHis2DateFrom.Value.ToShortDateString() + "' AND ";
                            break;
                        case "2":
                            filter += "CAST((SYS_TODOHIS.UPDATE_DATE " + connectMark + " ' ' " + connectMark + " SYS_TODOHIS.UPDATE_TIME) AS DATETIME) > '" + this.dtpHis2DateFrom.Value.ToShortDateString() + "' AND ";
                            break;
                        case "3":
                            filter += "to_date(SYS_TODOHIS.UPDATE_DATE " + connectMark + " ' ' " + connectMark + " SYS_TODOHIS.UPDATE_TIME, " + oracleDateFormat + ") > to_date('" + this.dtpHis2DateFrom.Value.ToShortDateString() + "', " + oracleDateFormat + ") AND ";
                            break;
                        case "4":
                            filter += string.Format("to_date(SYS_TODOHIS.UPDATE_DATE {0} ' ' {0} SYS_TODOHIS.UPDATE_TIME, {1}) > to_date('{2}', {1})  AND ", connectMark, informixDateFormat, this.dtpHis2DateFrom.Value.ToShortDateString());
                            break;
                        case "5":
                            filter += "CONCAT(SYS_TODOHIS.UPDATE_DATE, ' ', SYS_TODOHIS.UPDATE_TIME) > '" + this.dtpHis2DateFrom.Value.ToShortDateString() + "' AND ";
                            break;
                        case "6":
                            filter += string.Format("to_date(SYS_TODOHIS.UPDATE_DATE {0} ' ' {0} SYS_TODOHIS.UPDATE_TIME, {1}) > to_date('{2}', {1})  AND ", connectMark, informixDateFormat, this.dtpHis2DateFrom.Value.ToShortDateString());
                            break;
                    }
                }
            }
            if (this.dtpHis2DateTo.Checked)
            {
                if (myRet != null && myRet[0].ToString() == "0")
                {
                    switch (myRet[1].ToString())
                    {
                        case "1":
                            filter += "CAST((SYS_TODOHIS.UPDATE_DATE " + connectMark + " ' ' " + connectMark + " SYS_TODOHIS.UPDATE_TIME) AS DATETIME) < '" + this.dtpHis2DateTo.Value.ToShortDateString() + " 23:59:59' AND ";
                            break;
                        case "2":
                            filter += "CAST((SYS_TODOHIS.UPDATE_DATE " + connectMark + " ' ' " + connectMark + " SYS_TODOHIS.UPDATE_TIME) AS DATETIME) < '" + this.dtpHis2DateTo.Value.ToShortDateString() + " 23:59:59' AND ";
                            break;
                        case "3":
                            filter += "to_date(SYS_TODOHIS.UPDATE_DATE " + connectMark + " ' ' " + connectMark + " SYS_TODOHIS.UPDATE_TIME, " + oracleDateFormat + ") < to_date('" + this.dtpHis2DateTo.Value.ToShortDateString() + " 23:59:59', " + oracleDateFormat + ") AND ";
                            break;
                        case "4":
                            filter += string.Format("to_date(SYS_TODOHIS.UPDATE_DATE {0} ' ' {0} SYS_TODOHIS.UPDATE_TIME, {1}) < to_date('{2}', {1})  AND ", connectMark, informixDateFormat, this.dtpHis2DateTo.Value.ToShortDateString() + " 23:59:59");
                            break;
                        case "5":
                            filter += "CONCAT(SYS_TODOHIS.UPDATE_DATE, ' ', SYS_TODOHIS.UPDATE_TIME) < '" + this.dtpHis2DateTo.Value.ToShortDateString() + " 23:59:59' AND ";
                            break;
                        case "6":
                            filter += string.Format("to_date(SYS_TODOHIS.UPDATE_DATE {0} ' ' {0} SYS_TODOHIS.UPDATE_TIME, {1}) < to_date('{2}', {1})  AND ", connectMark, informixDateFormat, this.dtpHis2DateTo.Value.ToShortDateString() + " 23:59:59");
                            break;
                    }
                }
            }
            if (!string.IsNullOrEmpty(this.txtHis2Remark.Text))
            {
                filter += "SYS_TODOHIS.REMARK LIKE '%" + this.txtHis2Remark.Text + "%' AND ";
            }

            if (!string.IsNullOrEmpty(filter))
            {
                filter = filter.Substring(0, filter.LastIndexOf(" AND "));
            }

            this.wizToDoHis.Refresh(filter);

            this.panHis2Query.Visible = false;
            this.chkSubmitted.Enabled = true;
        }

        private void btnHis2QueryCancel_Click(object sender, EventArgs e)
        {
            this.panHis2Query.Visible = false;
            this.chkSubmitted.Enabled = true;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            String connectMark = "+";
            String DBAlias = CliUtils.fLoginDB;
            object[] myRet = CliUtils.CallMethod("GLModule", "GetDataBaseType", new object[] { DBAlias });
            if (myRet != null && myRet[0].ToString() == "0")
            {
                switch (myRet[1].ToString())
                {
                    case "1": connectMark = "+"; break;
                    case "2": connectMark = "+"; break;
                    case "3": connectMark = "||"; break;
                    case "4": connectMark = "||"; break;
                    case "5": connectMark = "||"; break;
                    case "6": connectMark = "||"; break;
                }
            }

            string filter = "";
            if (this.cmbHis2Flow.SelectedIndex > 0)
            {
                filter += "SYS_TODOHIS.FLOW_DESC='" + this.cmbHis2Flow.Text + "' AND ";
            }
            if (!string.IsNullOrEmpty(this.txtHis2DStep.Text))
            {
                filter += "SYS_TODOHIS.D_STEP_ID LIKE '" + this.txtHis2DStep.Text + "%' AND ";
            }
            if (!string.IsNullOrEmpty(this.txtHis2FormPresent.Text))
            {
                filter += "SYS_TODOHIS.FORM_PRESENT_CT LIKE '%'" + this.txtHis2FormPresent.Text + "%' AND ";
            }
            if (this.dtpHis2DateFrom.Checked)
            {
                if (myRet != null && myRet[0].ToString() == "0")
                {
                    switch (myRet[1].ToString())
                    {
                        case "1":
                            filter += "CAST((SYS_TODOHIS.UPDATE_DATE " + connectMark + " ' ' " + connectMark + " SYS_TODOHIS.UPDATE_TIME) AS DATETIME) > '" + this.dtpHis2DateFrom.Value.ToShortDateString() + "' AND ";
                            break;
                        case "2":
                            filter += "CAST((SYS_TODOHIS.UPDATE_DATE " + connectMark + " ' ' " + connectMark + " SYS_TODOHIS.UPDATE_TIME) AS DATETIME) > '" + this.dtpHis2DateFrom.Value.ToShortDateString() + "' AND ";
                            break;
                        case "3":
                            filter += "to_date(SYS_TODOHIS.UPDATE_DATE " + connectMark + " ' ' " + connectMark + " SYS_TODOHIS.UPDATE_TIME, " + oracleDateFormat + ") > to_date('" + this.dtpHis2DateFrom.Value.ToShortDateString() + "', " + oracleDateFormat + ") AND ";
                            break;
                        case "4":
                            filter += string.Format("to_date(SYS_TODOHIS.UPDATE_DATE {0} ' ' {0} SYS_TODOHIS.UPDATE_TIME, {1}) > to_date('{2}', {1})  AND ", connectMark, informixDateFormat, this.dtpHis2DateFrom.Value.ToShortDateString());
                            break;
                        case "5":
                            filter += "CONCAT(SYS_TODOHIS.UPDATE_DATE, ' ', SYS_TODOHIS.UPDATE_TIME) > '" + this.dtpHis2DateFrom.Value.ToShortDateString() + "' AND ";
                            break;
                        case "6":
                            filter += string.Format("to_date(SYS_TODOHIS.UPDATE_DATE {0} ' ' {0} SYS_TODOHIS.UPDATE_TIME, {1}) > to_date('{2}', {1})  AND ", connectMark, informixDateFormat, this.dtpHis2DateFrom.Value.ToShortDateString());
                            break;
                    }
                }
            }
            if (this.dtpHis2DateTo.Checked)
            {
                if (myRet != null && myRet[0].ToString() == "0")
                {
                    switch (myRet[1].ToString())
                    {
                        case "1":
                            filter += "CAST((SYS_TODOHIS.UPDATE_DATE " + connectMark + " ' ' " + connectMark + " SYS_TODOHIS.UPDATE_TIME) AS DATETIME) < '" + this.dtpHis2DateTo.Value.ToShortDateString() + " 23:59:59' AND ";
                            break;
                        case "2":
                            filter += "CAST((SYS_TODOHIS.UPDATE_DATE " + connectMark + " ' ' " + connectMark + " SYS_TODOHIS.UPDATE_TIME) AS DATETIME) < '" + this.dtpHis2DateTo.Value.ToShortDateString() + " 23:59:59' AND ";
                            break;
                        case "3":
                            filter += "to_date(SYS_TODOHIS.UPDATE_DATE " + connectMark + " ' ' " + connectMark + " SYS_TODOHIS.UPDATE_TIME, " + oracleDateFormat + ") < to_date('" + this.dtpHis2DateTo.Value.ToShortDateString() + " 23:59:59', " + oracleDateFormat + ") AND ";
                            break;
                        case "4":
                            filter += string.Format("to_date(SYS_TODOHIS.UPDATE_DATE {0} ' ' {0} SYS_TODOHIS.UPDATE_TIME, {1}) < to_date('{2}', {1})  AND ", connectMark, informixDateFormat, this.dtpHis2DateTo.Value.ToShortDateString() + " 23:59:59");
                            break;
                        case "5":
                            filter += "CONCAT(SYS_TODOHIS.UPDATE_DATE, ' ', SYS_TODOHIS.UPDATE_TIME) < '" + this.dtpHis2DateTo.Value.ToShortDateString() + " 23:59:59' AND ";
                            break;
                        case "6":
                            filter += string.Format("to_date(SYS_TODOHIS.UPDATE_DATE {0} ' ' {0} SYS_TODOHIS.UPDATE_TIME, {1}) < to_date('{2}', {1})  AND ", connectMark, informixDateFormat, this.dtpHis2DateTo.Value.ToShortDateString() + " 23:59:59");
                            break;
                    }
                }
            }
            if (!string.IsNullOrEmpty(this.txtHis2Remark.Text))
            {
                filter += "SYS_TODOHIS.REMARK LIKE '%" + this.txtHis2Remark.Text + "%' AND ";
            }

            if (!string.IsNullOrEmpty(filter))
            {
                filter = filter.Substring(0, filter.LastIndexOf(" AND "));
            }

            this.wizToDoHis.Refresh(filter);

            this.panHis2Query.Visible = false;
            this.chkSubmitted.Enabled = true;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.panHis2Query.Visible = false;
            this.chkSubmitted.Enabled = true;
        }

        private void btnHisQueryOK_Click(object sender, EventArgs e)
        {
            String connectMark = "+";
            String DBAlias = CliUtils.fLoginDB;
            object[] myRet = CliUtils.CallMethod("GLModule", "GetDataBaseType", new object[] { DBAlias });
            if (myRet != null && myRet[0].ToString() == "0")
            {
                switch (myRet[1].ToString())
                {
                    case "1": connectMark = "+"; break;
                    case "2": connectMark = "+"; break;
                    case "3": connectMark = "||"; break;
                    case "4": connectMark = "||"; break;
                    case "5": connectMark = "||"; break;
                    case "6": connectMark = "||"; break;
                }
            }

            string filter = "";
            if (this.cmbHisFlow.SelectedIndex > 0)
            {
                filter += "SYS_TODOLIST.FLOW_DESC='" + this.cmbHisFlow.Text + "' AND ";
            }
            if (!string.IsNullOrEmpty(this.txtHisDstep.Text))
            {
                filter += "SYS_TODOLIST.D_STEP_ID LIKE '" + this.txtHisDstep.Text + "%' AND ";
            }
            if (this.cmbHisSendTo.SelectedIndex > 0)
            {
                filter += "SYS_TODOLIST.SENDTO_NAME='" + this.cmbHisSendTo.Text + "' AND ";
            }
            if (!string.IsNullOrEmpty(this.txtHisFormPresent.Text))
            {
                filter += "SYS_TODOLIST.FORM_PRESENT_CT LIKE '%" + this.txtHisFormPresent.Text + "%' AND ";
            }
            if (this.dtpHisDateFrom.Checked)
            {
                if (myRet != null && myRet[0].ToString() == "0")
                {
                    switch (myRet[1].ToString())
                    {
                        case "1":
                            filter += "CAST((SYS_TODOLIST.UPDATE_DATE " + connectMark + " ' ' " + connectMark + " SYS_TODOLIST.UPDATE_TIME) AS DATETIME) > '" + this.dtpHisDateFrom.Value.ToShortDateString() + "' AND ";
                            break;
                        case "2":
                            filter += "CAST((SYS_TODOLIST.UPDATE_DATE " + connectMark + " ' ' " + connectMark + " SYS_TODOLIST.UPDATE_TIME) AS DATETIME) > '" + this.dtpHisDateFrom.Value.ToShortDateString() + "' AND ";
                            break;
                        case "3":
                            filter += "to_date(SYS_TODOLIST.UPDATE_DATE " + connectMark + " ' ' " + connectMark + " SYS_TODOLIST.UPDATE_TIME, " + oracleDateFormat + ") > to_date('" + this.dtpHisDateFrom.Value.ToShortDateString() + "', " + oracleDateFormat + ") AND ";
                            break;
                        case "4":
                            filter += string.Format("to_date(SYS_TODOLIST.UPDATE_DATE {0} ' ' {0} SYS_TODOLIST.UPDATE_TIME, {1}) > to_date('{2}', {1})  AND ", connectMark, informixDateFormat, this.dtpHisDateFrom.Value.ToShortDateString());
                            break;
                        case "5":
                            filter += "CONCAT(SYS_TODOLIST.UPDATE_DATE, ' ', SYS_TODOLIST.UPDATE_TIME) > '" + this.dtpHisDateFrom.Value.ToShortDateString() + "' AND ";
                            break;
                        case "6":
                            filter += string.Format("to_date(SYS_TODOLIST.UPDATE_DATE {0} ' ' {0} SYS_TODOLIST.UPDATE_TIME, {1}) > to_date('{2}', {1})  AND ", connectMark, informixDateFormat, this.dtpHisDateFrom.Value.ToShortDateString());
                            break;
                    }
                }
            }
            if (this.dtpHisDateTo.Checked)
            {
                if (myRet != null && myRet[0].ToString() == "0")
                {
                    switch (myRet[1].ToString())
                    {
                        case "1":
                            filter += "CAST((SYS_TODOLIST.UPDATE_DATE " + connectMark + " ' ' " + connectMark + " SYS_TODOLIST.UPDATE_TIME) AS DATETIME) < '" + this.dtpHisDateTo.Value.ToShortDateString() + " 23:59:59' AND ";
                            break;
                        case "2":
                            filter += "CAST((SYS_TODOLIST.UPDATE_DATE " + connectMark + " ' ' " + connectMark + " SYS_TODOLIST.UPDATE_TIME) AS DATETIME) < '" + this.dtpHisDateTo.Value.ToShortDateString() + " 23:59:59' AND ";
                            break;
                        case "3":
                            filter += "to_date(SYS_TODOLIST.UPDATE_DATE " + connectMark + " ' ' " + connectMark + " SYS_TODOLIST.UPDATE_TIME, " + oracleDateFormat + ") < to_date('" + this.dtpHisDateTo.Value.ToShortDateString() + " 23:59:59', " + oracleDateFormat + ") AND ";
                            break;
                        case "4":
                            filter += string.Format("to_date(SYS_TODOLIST.UPDATE_DATE {0} ' ' {0} SYS_TODOLIST.UPDATE_TIME, {1}) < to_date('{2}', {1})  AND ", connectMark, informixDateFormat, this.dtpHisDateTo.Value.ToShortDateString() + " 23:59:59");
                            break;
                        case "5":
                            filter += "CONCAT(SYS_TODOLIST.UPDATE_DATE, ' ', SYS_TODOLIST.UPDATE_TIME) < '" + this.dtpHisDateTo.Value.ToShortDateString() + " 23:59:59' AND ";
                            break;
                        case "6":
                            filter += string.Format("to_date(SYS_TODOLIST.UPDATE_DATE {0} ' ' {0} SYS_TODOLIST.UPDATE_TIME, {1}) < to_date('{2}', {1})  AND ", connectMark, informixDateFormat, this.dtpHisDateTo.Value.ToShortDateString() + " 23:59:59");
                            break;
                    }
                }
            }
            if (!string.IsNullOrEmpty(this.txtHisRemark.Text))
            {
                filter += "SYS_TODOLIST.REMARK LIKE '%" + this.txtHisRemark.Text + "%' AND ";
            }

            if (!string.IsNullOrEmpty(filter))
            {
                filter = filter.Substring(0, filter.LastIndexOf(" AND "));
            }

            this.wizToDoHis.Refresh(filter);

            this.panHisQuery.Visible = false;
            this.chkSubmitted.Enabled = true;
        }

        private void btnHisQueryCancel_Click(object sender, EventArgs e)
        {
            this.panHisQuery.Visible = false;
            this.chkSubmitted.Enabled = true;
        }

        private void pbGo_Click(object sender, EventArgs e)
        {
            //if (tbGO.Text == "")
            //{
            //    MessageBox.Show("Please enter a menu first.");
            //}
            //else
            //{
            //    Boolean flag = false;
            //    for (int i = 0; i < this.tView.Nodes.Count; i++)
            //    {
            //        if (compareCaption(tbGO.Text, this.tView.Nodes[i].Text.ToString()))
            //        {
            //            showForm(this.tView.Nodes[i].Tag.ToString(), tView.Nodes[i].Text);
            //            flag = true;
            //            break;
            //        }
            //        flag = getChildNode(this.tView.Nodes[i], tbGO.Text);
            //        if (flag) break;
            //    }
            //    if (!flag)
            //    {
            //        MessageBox.Show("The menu you entered is not exist.");
            //    }
            //}
        }

        public Boolean getChildNode(TreeNode tn, String text)
        {
            if (compareCaption(text, tn.Text.ToString()))
            {
                showForm(tn.Tag.ToString(), tn.Text);
                return true; ;
            }
            if (tn.Nodes.Count > 0)
            {
                for (int i = 0; i < tn.Nodes.Count; i++)
                {
                    if (compareCaption(text, tn.Nodes[i].Text.ToString()))
                    {
                        showForm(tn.Nodes[i].Tag.ToString(), tn.Nodes[i].Text);
                        return true; ;
                    }
                    if (getChildNode(tn.Nodes[i], text)) return true;
                }
            }
            return false;
        }

        private bool compareCaption(String text, String nodeText)
        {
            if (nodeText.StartsWith(text))
                return true;
            else
                return false;
        }

        private void pbGo_MouseLeave(object sender, EventArgs e)
        {
            string s = Application.StartupPath + "\\Resources\\MenuGO.gif";
            this.pbGo.ImageLocation = s;
        }

        private void pbGo_MouseMove(object sender, MouseEventArgs e)
        {
            string s = Application.StartupPath + "\\Resources\\MenuGO2.gif";
            this.pbGo.ImageLocation = s;
        }

        private void pbMyFavor_Click(object sender, EventArgs e)
        {
            frmFavorMenu ffm = new frmFavorMenu(MenuIDList, CaptionList, ParentList);
            ffm.ShowDialog();
            if (ffm.result)
            {
                ItemToGet();
            }
        }

        private void pbMyFavor_MouseLeave(object sender, EventArgs e)
        {
            string s = Application.StartupPath + "\\Resources\\AddFavor.png";
            this.pbMyFavor.ImageLocation = s;
        }

        private void pbMyFavor_MouseMove(object sender, MouseEventArgs e)
        {
            string s = Application.StartupPath + "\\Resources\\AddFavor2.png";
            this.pbMyFavor.ImageLocation = s;
        }

        private void CheckPassword(String userid)
        {
            DateTime date = new DateTime();
            DateTime today = DateTime.Today;
            String value = "";
            object[] param = new object[3];
            param[0] = userid;

            object[] myRet = CliUtils.CallMethod("GLModule", "GetPasswordLastDate", param);
            if (myRet != null && myRet[0].ToString() == "0")
            {
                if (myRet[1] == DBNull.Value || myRet[1].ToString() == "")
                    value = "new";
                else
                {
                    date = DateTime.ParseExact(myRet[1].ToString(), "yyyyMMdd", null);
                    TimeSpan ts = today - date;
                    value = ts.TotalDays.ToString();
                }
            }

            if (value == "new")
            {
                SYS_LANGUAGE language = CliUtils.fClientLang;
                string message = SysMsg.GetSystemMessage(CliUtils.fClientLang, "EEPNetClient", "FrmClientMain", "NewPassword");
                MessageBox.Show(message);

                CliUtils.CallMethod("GLModule", "LogOut", new object[] { (object)(CliUtils.fLoginUser) });
                frmUserPWD fupwd = new frmUserPWD();
                fupwd.ShowDialog();
                if (!fupwd.upwdControl1.isOK)
                    Environment.Exit(0);
                else
                {
                    string sParam = CliUtils.fLoginUser + ':' + CliUtils.fLoginPassword + ':' + CliUtils.fLoginDB + ':' + "0";
                    CliUtils.CallMethod("GLModule", "CheckUser", new object[] { (object)sParam });
                }
            }
            else
            {
                if (Convert.ToInt32(value) > CliUtils.fPassWordExpiry)
                {
                    SYS_LANGUAGE language = CliUtils.fClientLang;
                    string message = SysMsg.GetSystemMessage(CliUtils.fClientLang, "EEPNetClient", "FrmClientMain", "PasswordAnnulment");
                    MessageBox.Show(message);
                    CliUtils.CallMethod("GLModule", "LogOut", new object[] { (object)(CliUtils.fLoginUser) });
                    frmUserPWD fupwd = new frmUserPWD();
                    fupwd.ShowDialog();
                    if (!fupwd.upwdControl1.isOK)
                        Environment.Exit(0);
                }
                else if ((CliUtils.fPassWordExpiry - Convert.ToInt32(value)) <= CliUtils.fPassWordNotify)
                {
                    SYS_LANGUAGE language = CliUtils.fClientLang;
                    string message = SysMsg.GetSystemMessage(CliUtils.fClientLang, "EEPNetClient", "FrmClientMain", "PasswordNotify");
                    MessageBox.Show(String.Format(message, CliUtils.fPassWordExpiry - Convert.ToInt32(value)));
                }
            }
        }

        private void dgvToDoList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvToDoList.CurrentRow != null)
                this.wizToDoList.OpenFlowDetail(this.dgvToDoList.CurrentRow.DataBoundItem);
        }

        private void dgvToDoList_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                if (this.dgvToDoList.Columns["colImportant"].Index == e.ColumnIndex)
                {
                    object obj = dgvToDoList.Rows[e.RowIndex].DataBoundItem;
                    if (obj != null && obj is DataRowView)
                    {
                        DataRowView rowView = (DataRowView)obj;
                        if (rowView["FLOWIMPORTANT"].ToString() == "0")
                        {
                            paintNullImageCell(dgvToDoList, e);
                        }
                    }
                }
                else if (this.dgvToDoList.Columns["colUrgent"].Index == e.ColumnIndex)
                {
                    object obj = dgvToDoList.Rows[e.RowIndex].DataBoundItem;
                    if (obj != null && obj is DataRowView)
                    {
                        DataRowView rowView = (DataRowView)obj;
                        if (rowView["FLOWURGENT"].ToString() == "0")
                        {
                            paintNullImageCell(dgvToDoList, e);
                        }
                    }
                }
                else if (this.dgvToDoList.Columns["colStatus"].Index == e.ColumnIndex)
                {
                    paintStatusCell(this.dgvToDoList, e);
                }
            }
        }

        private void dgvToDoList_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            foreach (DataGridViewRow row in this.dgvToDoList.Rows)
            {
                row.ContextMenuStrip = this.cmsToDoList;
            }
        }

        private void dgvToDoList_Sorted(object sender, EventArgs e)
        {
            this.setToDoListOvertimeWarning();
        }

        private void paintNullImageCell(DataGridView grid, DataGridViewCellPaintingEventArgs e)
        {
            Rectangle newRect = new Rectangle(e.CellBounds.X + 1, e.CellBounds.Y + 1, e.CellBounds.Width - 2, e.CellBounds.Height - 2);
            using (Brush gridBrush = new SolidBrush(grid.GridColor),
                backColorBrush = new SolidBrush(e.CellStyle.BackColor),
                selectionBackColorBrush = new SolidBrush(e.CellStyle.SelectionBackColor))
            {
                using (Pen gridLinePen = new Pen(gridBrush))
                {
                    if (grid[e.ColumnIndex, e.RowIndex].Selected)
                    {
                        e.Graphics.FillRectangle(selectionBackColorBrush, e.CellBounds);
                    }
                    else
                    {
                        e.Graphics.FillRectangle(backColorBrush, e.CellBounds);
                    }
                    e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left - 1, e.CellBounds.Bottom - 1, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);
                    e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left - 1, e.CellBounds.Top - 1, e.CellBounds.Right - 1, e.CellBounds.Top - 1);
                    e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left - 1, e.CellBounds.Top - 1, e.CellBounds.Left - 1, e.CellBounds.Bottom - 1);
                    e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1, e.CellBounds.Top - 1, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);
                    e.Handled = true;
                }
            }
        }

        void paintStatusCell(DataGridView grid, DataGridViewCellPaintingEventArgs e)
        {
            Rectangle newRect = new Rectangle(e.CellBounds.X + 1, e.CellBounds.Y + 1, e.CellBounds.Width - 4, e.CellBounds.Height - 4);
            using (Brush gridBrush = new SolidBrush(grid.GridColor), backColorBrush = new SolidBrush(e.CellStyle.BackColor), selectionBackColorBrush = new SolidBrush(e.CellStyle.SelectionBackColor))
            {
                using (Pen gridLinePen = new Pen(gridBrush))
                {
                    // Erase the cell.
                    if (grid.Rows[e.RowIndex].Selected)
                    {
                        e.Graphics.FillRectangle(selectionBackColorBrush, e.CellBounds);
                    }
                    else
                    {
                        e.Graphics.FillRectangle(backColorBrush, e.CellBounds);
                    }

                    // Draw the grid lines (only the right and bottom lines;
                    // DataGridView takes care of the others).
                    e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);
                    e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1, e.CellBounds.Top, e.CellBounds.Right - 1, e.CellBounds.Bottom);
                }
            }
            using (Brush foreColorBrush = new SolidBrush(e.CellStyle.ForeColor), selectionForeColorBrush = new SolidBrush(e.CellStyle.SelectionForeColor))
            {
                string formatValue = "";
                switch (e.Value.ToString())
                {
                    case "Z":
                        formatValue = lstStatus[0];
                        break;
                    case "N":
                        formatValue = lstStatus[1];
                        break;
                    case "NR":
                        formatValue = lstStatus[2];
                        break;
                    case "NF":
                        formatValue = lstStatus[3];
                        break;
                    case "X":
                        formatValue = lstStatus[4];
                        break;
                    case "A":
                        formatValue = lstStatus[5];
                        break;
                }

                if (grid.Rows[e.RowIndex].Selected)
                {
                    e.Graphics.DrawString(formatValue, e.CellStyle.Font, selectionForeColorBrush, e.CellBounds.X + 2, e.CellBounds.Y + 4);
                }
                else
                {
                    e.Graphics.DrawString(formatValue, e.CellStyle.Font, foreColorBrush, e.CellBounds.X + 2, e.CellBounds.Y + 4);
                }
                e.Handled = true;
            }
        }

        private void dgvToDoHis_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex != -1)
                dgvToDoHis.Rows[e.RowIndex].ContextMenuStrip = this.cmsToDoHis;
        }

        private void dgvToDoHis_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dgvToDoHis.CurrentRow != null)
                this.wizToDoHis.OpenFlowDetail(this.dgvToDoHis.CurrentRow.DataBoundItem);
        }

        private void dgvToDoHis_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.RowIndex >= 0)
            {

                if (this.dgvToDoHis.Columns["colImportant"] != null && this.dgvToDoHis.Columns["colImportant"].Index == e.ColumnIndex)
                {
                    object obj = dgvToDoHis.Rows[e.RowIndex].DataBoundItem;
                    if (obj != null && obj is DataRowView)
                    {
                        DataRowView rowView = (DataRowView)obj;
                        if (rowView["FLOWIMPORTANT"].ToString() == "0")
                        {
                            paintNullImageCell(dgvToDoHis, e);
                        }
                    }
                }
                else if (this.dgvToDoHis.Columns["colUrgent"] != null && this.dgvToDoHis.Columns["colUrgent"].Index == e.ColumnIndex)
                {
                    object obj = dgvToDoHis.Rows[e.RowIndex].DataBoundItem;
                    if (obj != null && obj is DataRowView)
                    {
                        DataRowView rowView = (DataRowView)obj;
                        if (rowView["FLOWURGENT"].ToString() == "0")
                        {
                            paintNullImageCell(dgvToDoHis, e);
                        }
                    }
                }
                else if (this.dgvToDoList.Columns["colStatus"].Index == e.ColumnIndex)
                {
                    paintStatusCell(this.dgvToDoHis, e);
                }
            }
        }

        private void dgvToDoHis_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            foreach (DataGridViewRow row in this.dgvToDoHis.Rows)
            {
                row.ContextMenuStrip = this.cmsToDoHis;
            }
        }

        private void dgvToDoHis_Sorted(object sender, EventArgs e)
        {
            this.setToDoHisOvertimeWarning();
        }

        private void dgvNotify_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex != -1)
                dgvNotify.Rows[e.RowIndex].ContextMenuStrip = this.cmsNotify;
        }

        private void dgvNotify_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvNotify.CurrentRow != null)
                this.wizNotify.OpenFlowDetail(this.dgvNotify.CurrentRow.DataBoundItem);
        }

        private void dgvNotify_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                if (this.dgvNotify.Columns["colImportant"].Index == e.ColumnIndex)
                {
                    object obj = dgvNotify.Rows[e.RowIndex].DataBoundItem;
                    if (obj != null && obj is DataRowView)
                    {
                        DataRowView rowView = (DataRowView)obj;
                        if (rowView["FLOWIMPORTANT"].ToString() == "0")
                        {
                            paintNullImageCell(dgvNotify, e);
                        }
                    }
                }
                else if (this.dgvNotify.Columns["colUrgent"].Index == e.ColumnIndex)
                {
                    object obj = dgvNotify.Rows[e.RowIndex].DataBoundItem;
                    if (obj != null && obj is DataRowView)
                    {
                        DataRowView rowView = (DataRowView)obj;
                        if (rowView["FLOWURGENT"].ToString() == "0")
                        {
                            paintNullImageCell(dgvNotify, e);
                        }
                    }
                }
                else if (this.dgvToDoList.Columns["colStatus"].Index == e.ColumnIndex)
                {
                    paintStatusCell(this.dgvNotify, e);
                }
            }
        }

        private void dgvNotify_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            foreach (DataGridViewRow row in this.dgvNotify.Rows)
            {
                row.ContextMenuStrip = this.cmsNotify;
            }
        }

        private void dgvNotify_Sorted(object sender, EventArgs e)
        {
            this.setNotifyOvertimeWarning();
        }

        private void dgvOvertime_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dgvOvertime.CurrentRow != null)
                this.wizOvertime.OpenFlowDetail(this.dgvOvertime.CurrentRow.DataBoundItem);
        }

        private void dgvToDoList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex != -1)
                dgvToDoList.Rows[e.RowIndex].ContextMenuStrip = this.cmsToDoList;
        }

        private void cmsToDoList_Opened(object sender, EventArgs e)
        {
            if (this.dgvToDoList.CurrentRow != null)
            {
                DataRowView rowView = this.dgvToDoList.CurrentRow.DataBoundItem as DataRowView;
                string flowNavMode = rowView["FLNAVIGATOR_MODE"].ToString();
                switch (flowNavMode)
                {
                    case "0": //Submit
                    case "3": //Notify
                    case "4": //Inquery
                    case "6": //None
                        this.approveToolStripMenuItem.Enabled = false;
                        this.rejectToolStripMenuItem.Enabled = false;
                        this.returnToolStripMenuItem.Enabled = false;
                        this.openToolStripMenuItem.Enabled = true;
                        break;
                    case "1": //Approve
                    case "5": //Continue
                        this.approveToolStripMenuItem.Enabled = true;
                        this.rejectToolStripMenuItem.Enabled = false;
                        this.returnToolStripMenuItem.Enabled = true;
                        this.openToolStripMenuItem.Enabled = true;
                        break;
                    case "2": //Return
                        this.approveToolStripMenuItem.Enabled = false;
                        this.rejectToolStripMenuItem.Enabled = true;
                        this.returnToolStripMenuItem.Enabled = false;
                        this.openToolStripMenuItem.Enabled = true;
                        break;
                }

                string status = rowView["STATUS"].ToString();
                if (status == "A")
                {
                    this.returnToolStripMenuItem.Enabled = false;
                }
                object plusRoles = rowView["PLUSROLES"];
                if (plusRoles != null && plusRoles.ToString() != "")
                {
                    this.approveToolStripMenuItem.Enabled = false;
                    this.returnToolStripMenuItem.Enabled = false;
                }
            }
            else
            {
                this.approveToolStripMenuItem.Enabled = false;
                this.rejectToolStripMenuItem.Enabled = false;
                this.returnToolStripMenuItem.Enabled = false;
                this.openToolStripMenuItem.Enabled = false;
                this.refreshToolStripMenuItem.Enabled = true;
            }
        }

        private void approveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.wizToDoList.Approve();
            this.wizToDoList.Refresh();
            this.wizToDoHis.Refresh();
        }

        private void rejectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.wizToDoList.Reject();
            this.wizToDoList.Refresh();
            this.wizToDoHis.Refresh();
        }

        private void returnToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.wizToDoList.Return();
            this.wizToDoList.Refresh();
            this.wizToDoHis.Refresh();
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dgvToDoList.CurrentRow != null)
                this.wizToDoList.OpenFlowDetail(dgvToDoList.CurrentRow.DataBoundItem);
        }

        private void refreshToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.wizToDoList.Refresh();
        }

        private void flowDeleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.wizNotify.DeleteNotify();
        }

        private void cmsToDoHis_Opened(object sender, EventArgs e)
        {
            if (this.dgvToDoHis.CurrentRow != null)
            {
                if (this.wizToDoHis.SqlMode == ESqlMode.ToDoHis)
                {
                    this.returnToolStripMenuItem1.Enabled = true;
                }
                else if (this.wizToDoHis.SqlMode == ESqlMode.FlowRunOver)
                {
                    this.returnToolStripMenuItem1.Enabled = false;
                }
            }
            else
            {
                this.returnToolStripMenuItem1.Enabled = false;
                this.openToolStripMenuItem1.Enabled = false;
                this.refreshToolStripMenuItem1.Enabled = true;
            }
        }

        private void returnToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (this.dgvToDoHis.SelectedRows != null && this.dgvToDoHis.SelectedRows.Count == 1)
            {
                DataRowView row = (DataRowView)this.dgvToDoHis.SelectedRows[0].DataBoundItem;
                string stepid = row["D_STEP_ID"].ToString();
                this.wizToDoHis.Return(stepid);
            }
        }

        private void openToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (this.dgvToDoHis.CurrentRow != null)
                this.wizToDoHis.OpenFlowDetail(this.dgvToDoHis.CurrentRow);
        }

        private void refreshToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.wizToDoHis.Refresh();
        }

        private void openToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            if (this.dgvNotify.CurrentRow != null)
                this.wizNotify.OpenFlowDetail(this.dgvNotify.CurrentRow.DataBoundItem);
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.wizNotify.DeleteNotify();
        }

        private void refreshToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            this.wizNotify.Refresh();
        }

        private void tmMessage_Tick(object sender, EventArgs e)
        {
            frmMessage frm = new frmMessage();

            DataSet ds = CliUtils.GetMessage();
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                frm.dataGridView1.DataSource = ds;
                frm.dataGridView1.DataMember = "Message";
                frm.Location = new Point(Screen.AllScreens[0].WorkingArea.Width - frm.Size.Width, Screen.AllScreens[0].WorkingArea.Height - frm.Size.Height);
                frm.Show();
            }
        }

        private void tmFlow_Tick(object sender, EventArgs e)
        {
            this.wizToDoList.Refresh();
            this.wizToDoHis.Refresh();
            this.wizNotify.Refresh();
            this.setToDoListOvertimeWarning();
            if (this.wizToDoHis.SqlMode != ESqlMode.FlowRunOver)
            {
                this.setToDoHisOvertimeWarning();
            }
            this.setNotifyOvertimeWarning();
        }

        private void solutionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CurProject aForm = new CurProject(this);
            aForm.ShowDialog();
        }

        private void dataBaseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmDataBase dbForm = new frmDataBase(this);
            dbForm.ShowDialog();
        }

        private void changePasswordToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmUserPWD fupwd = new frmUserPWD();
            fupwd.ShowDialog();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void aboutEEPNetClientToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormVersion form = new FormVersion("关于M3系统");
            form.Ab_SystemName = "M3 钢结构项目管理系统 (Ver 2.0)";
            form.Ab_SystemCopyRight = "美联钢结构建筑系统(上海)有限公司 版权所有";
            form.Ab_SystemDes = @"本系统由美联IT程序开发团队：唐文明,金卫明,马叶晶等开发;如使用中有问题,请致电021-67748188-1371或Email;wmtang@usas.com.cn联系";
            form.Ab_SystemPicture = global::EEPNetFLClient.Properties.Resources.M3s ;
            form.ShowDialog(this);

            
        }

        private void miVwTreeMenu_Click(object sender, EventArgs e)
        {            
            this.scMaster.Panel1Collapsed = !(sender as ToolStripMenuItem).Checked;
        }

        private void miVwWFManage_Click(object sender, EventArgs e)
        {
            this.panFLContainer.Visible = (sender as ToolStripMenuItem).Checked;
            tmFlow.Enabled = this.panFLContainer.Visible;
        }

        private void miVwSatatusBar_Click(object sender, EventArgs e)
        {
            this.staMain.Visible = (sender as ToolStripMenuItem).Checked;
        }

        private void frmClientFL_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (CliUtils.fLoginUser != "") //已经登录过才执行此操作，有可能在frmLogin时取消则忽略
            {
                if (MessageBox.Show("你确信退出\r\n\r\n美联钢构项目管理信息系统 吗?", 
                    "信息提示", 
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                {
                    e.Cancel = true;
                    return;
                }
                EEPNetFLClient.Properties.Settings.Default.ShowTree = !this.scMaster.Panel1Collapsed ? "1" : "0";
                EEPNetFLClient.Properties.Settings.Default.ShowFL = this.panFLContainer.Visible ? "1" : "0";
                EEPNetFLClient.Properties.Settings.Default.ShowStaBar = this.staMain.Visible ? "1" : "0";
                EEPNetFLClient.Properties.Settings.Default.FLHeight = this.panFLContainer.Height;
                EEPNetFLClient.Properties.Settings.Default.TreeWidth = this.scMaster.SplitterDistance;
                EEPNetFLClient.Properties.Settings.Default.AlwaysUpdateCache = this.miUpdateCache.Checked;
                EEPNetFLClient.Properties.Settings.Default.Save();
            }
        }

        /// <summary>
        /// 展开上次关闭前最后单击的一个节点
        /// </summary>
        private void ExpandTreeMenu()
        {
            string _lastClickX = Properties.Settings.Default.LastClick;
            string[] _sarr = _lastClickX.Split('|');
            if (_sarr.Length == 3)
            {
                int nppSelectIndex = Convert.ToInt32(_sarr[0]);
                string tvName = _sarr[1];
                string ndName = _sarr[2];
                if (nppSelectIndex < this.onavMaster.NavigationPages.Count)
                {
                    Ascend.Windows.Forms.NavigationPanePage npp = this.onavMaster.NavigationPages[nppSelectIndex];
                    if (npp != null)
                    {
                        this.onavMaster.SelectedIndex = nppSelectIndex;
                        TreeView[] _tvs = npp.Controls.Find(tvName, false) as TreeView[];
                        if (_tvs!=null && _tvs.Length > 0)
                        {
                            TreeView tv = _tvs[0];
                            if (tv != null)
                            {
                                TreeNode[] _tns = tv.Nodes.Find(ndName, true);
                                if (_tns.Length == 0) return;
                                TreeNode _tn = _tns[0];
                                tv.SelectedNode = _tn;
                                while (_tn.Parent != null)
                                {
                                    _tn.Parent.Expand();
                                    _tn = _tn.Parent;
                                }
                                tv.Focus();
                            }
                        }
                    }
                }
            }                  
        }
              
        /// <summary>
        /// 更新客户端数据缓存
        /// </summary>
        private void LoadCachDataSet(object sender, EventArgs e)
        {
            try
            {
                //如果用户未设定允许更新数据缓存则退出
                if (!this.miUpdateCache.Checked)
                    return;

                //如果在局域网内使用不需要压缩
                string[] _serverIp = Srvtools.CliUtils.fRemoteIP.Split('.');
                string[] _localTp = Srvtools.CliUtils.fComputerIp.Split('.');
                bool _dataCompressed = !(_serverIp[0] == _localTp[0] && _serverIp[1] == _localTp[1]);

                frmWaiting.ShowWaiting(sender==null, "正在加载需要更新文件列表...");                
                
                String sql = "SELECT Id, RemoteName, CacheFile, UserGroup FROM SysInitCache Where Solution='" + Srvtools.CliUtils.fLoginDB + "' ";
                DataSet ds = CliUtils.ExecuteSql("GLModule", "cmdRefValUse", sql, true, CliUtils.fCurrentProject);
                int count = ds.Tables[0].Rows.Count;
                for (int i = 0; i < count; i++)
                {
                    string RemoteName = ds.Tables[0].Rows[i]["RemoteName"].ToString();
                    string CacheFile = ds.Tables[0].Rows[i]["CacheFile"].ToString();

                    frmWaiting.UpdateMessage(String.Format("更新客户端数据缓存,总计 {0} 项.\r\n正在更新第 {1} 项: [{2}].\r\n请稍候...",
                                            count,i + 1,CacheFile));

                    cdsMain.RemoteName = RemoteName;
                    cdsMain.CacheFile = CacheFile;
                    cdsMain.DataCompressed = _dataCompressed;
                    cdsMain.SetWhere("");
                    cdsMain.GetData(CacheModeType.All);
                    cdsMain.Active = true;
                    cdsMain.Save();                    
                }                
            }
            catch (Exception ex)
            {
                MessageBox.Show("更新缓存数据失败:                                 \r\n\r\n" + ex.Message, 
                    "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                frmWaiting.CloseWaiting();                
            }
        }

        private void miUpdateCache_Click(object sender, EventArgs e)
        {
            LoadCachDataSet(sender,e);
        }

        private void miHelpDir_Click(object sender, EventArgs e)
        {
            string _help =Application.StartupPath+"\\config\\MbpmHelp.chm";
            if (System.IO.File.Exists(_help))
            {
                Help.ShowHelp(this, _help);
            }
            else
            {
                MessageBox.Show("暂没有安装帮助文件.                                ", 
                    "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void miHelpIndex_Click(object sender, EventArgs e)
        {
            string _help = Application.StartupPath + "\\config\\MbpmHelp.chm";
            if (System.IO.File.Exists(_help))
            {
                Help.ShowHelpIndex(this, _help);
            }
            else
            {
                MessageBox.Show("暂没有安装帮助文件.                                ", 
                    "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        void frmClientFL_HelpRequested(object sender, HelpEventArgs hlpevent)
        {
            miHelpDir_Click(null,null);
            hlpevent.Handled = true;
        }

        /// <summary>
        /// 窗体第一次显示时执行此事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmClientFL_Shown(object sender, EventArgs e)
        {
            try
            {
                ExpandTreeMenu();
                ShowUpdateHistory();                
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message,"错误提示",MessageBoxButtons.OK ,MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 显示系统最新更新
        /// </summary>
        private void ShowUpdateHistory()
        {
            System.Threading.Thread _th = new System.Threading.Thread(new System.Threading.ThreadStart(ShowfrmUH));
            _th.SetApartmentState(System.Threading.ApartmentState.STA);
            _th.Start();                            
        }

        string m_SvrLastUpdate = "";
        /// <summary>
        /// 当用户对某项更新还没有看过或看过次数少于3则会显示更新
        /// </summary>
        private void ShowfrmUH()
        {
            System.Threading.Thread.Sleep(3000); //延迟
            try
            {
                string updatehistory = Application.StartupPath + "\\UpdateHistory.xml";
                bool MustUpdate = false;
                object[] result = null;
                System.Data.DataTable _dt = null;
                string cDate = "";                
                result = Srvtools.CliUtils.CallMethod("sAdm", "GetUpdateInfo", null);
                if (result != null && (int)result[0] == 0)
                {
                    m_SvrLastUpdate = result[1].ToString();
                }
                if (!System.IO.File.Exists(updatehistory))  //如不存在记录更历史的文件将会自动更新
                {
                    MustUpdate = true;
                }
                else                                        //存在文件，取出该文件记录的日期及服务端最新更新日期 并比较是否相同                
                {
                    System.Xml.XmlDocument xdoc = new System.Xml.XmlDocument();
                    xdoc.Load(updatehistory);
                    System.Xml.XmlNode xNode = null;
                    System.Xml.XmlElement xElem = null;
                    xNode = xdoc.SelectSingleNode("//Update/History");
                    xElem = (System.Xml.XmlElement)xNode.SelectSingleNode("//Last");
                    if (xElem != null)
                    {
                        cDate = xElem.InnerText;
                    }
                    if (cDate != m_SvrLastUpdate)
                        MustUpdate = true;
                }
                if (MustUpdate) //必须更新
                {
                    MessageBox.Show(this,"尊敬的用户:\r\n由于升级程序检测到系统有新版本,\r\n" +
                        "以下步骤会自动执行系统更新升级,\r\n" +
                        "在此过程中可能会重启本系统,由此给您带来不便,敬请谅解!", "更新提示",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);                    
                    ClientUpdate();
                }

                //显示更新说明
                string sUser = Srvtools.CliUtils.fLoginUser;
                result = Srvtools.CliUtils.CallMethod("sAdm", "GetUpdateMaxRowId", new object[] { sUser, "" });
                if (result != null && (int)result[0] == 0)
                {
                    _dt = result[2] as DataTable;
                    int _count = Convert.ToInt32(_dt.Rows[0][0]);
                    if (_count > 0)
                    {
                        frmUpdateHistory _frmUH = new frmUpdateHistory(_count);
                        _frmUH.ShowInTaskbar = false;
                        _frmUH.ShowDialog(this);
                    }
                }
                //显最新更新时间
                this.Text += " 更新时间:" + m_SvrLastUpdate;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 以IP 为标志检查是否有最新更新
        /// </summary>
        private void ClientUpdate()
        {
            try
            {
                frmWaiting.ShowWaiting(false, "正在获取需要下载的文件列表.");
                System.Threading.Thread.Sleep(300);

                object[] _rtn = CliUtils.CallMethod("GLModule", "GetClientUpdateFiles",
                    new object[] { CliUtils.fCurrentProject, "", null, true });
                if (_rtn != null && (int)_rtn[0] == 0)
                {
                    string[] _filesSvr = _rtn[1].ToString().Split(';');
                    string[] _filesClt = _rtn[2].ToString().Split(';');

                    string _downloadtemp = String.Format("{0}\\DownLoadTemp", Application.StartupPath);
                    if (Directory.Exists(_downloadtemp))
                        Directory.Delete(_downloadtemp, true);

                    int count = _filesSvr.Length;
                    frmWaiting.UpdateMessage("需要下载的文件数量为 " + count.ToString());
                    System.Threading.Thread.Sleep(300);

                    for (int i = 0; i < _filesSvr.Length; i++)
                    {
                        //如果是客户端更新文件直接下到外层,达到自已更新自已目的.
                        if (_filesClt[i].ToLower().EndsWith("eepclientupdate.exe"))
                            Srvtools.CliUtils.DownLoad(_filesSvr[i], Application.StartupPath + _filesClt[i]);
                        else
                            Srvtools.CliUtils.DownLoad(_filesSvr[i], _downloadtemp + _filesClt[i]);

                        frmWaiting.UpdateMessage(String.Format("已下载文件 {0}/{1}.", i + 1, count));
                        System.Threading.Thread.Sleep(30);
                    }

                    frmWaiting.UpdateMessage("下载完成,将关闭主程序,执行文件替换，请稍候...");
                    System.Threading.Thread.Sleep(1500);

                    CliUtils.fLoginUser = ""; //此处清除已登录信息，不然会提示用户是否关闭
                    Application.Exit();

                    System.Diagnostics.Process.Start("EEPClientUpdate.exe", this.m_SvrLastUpdate);
                }
            }
            catch (Exception e1)
            {
                frmWaiting.CloseWaiting();
                MessageBox.Show(e1.Message);
            }
            finally
            {
                frmWaiting.CloseWaiting();
            }
        }

        private void miUpdateClient_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("您选择了手动系统升级,\r\n" +
                        "在此过程中可能会重启本系统,如果您有未保存的操作,请先单击取消按钮.\r\n" +
                        "待您先保存好所有的修改后,再执行此操作.\r\n"+
                        "由此给您带来不便,敬请谅解!", "更新提示",
                        MessageBoxButtons.OKCancel, MessageBoxIcon.Question)==DialogResult.OK)
            {
                ClientUpdate();
            }
        }

        private void logouttoolStripMenuItem_Click(object sender, EventArgs e)
        {
            Srvtools.CliUtils.fLoginUser = "";
            Application.Exit();
            System.Diagnostics.Process.Start("EEPNetFLClient.exe");
        }
    }
}
